I am drawing a blank on how best to go about this task. I basically need to write some SQL for an Access db that will take data more or less in the following format:
State Lost Name
NY no A
NY no B
NY yes C
NY no D
MD yes E
MD yes F
VA no G
VA yes H
And I need a query to return the following:
State CountLost Total in State
NY 1 4
MD 2 2
VA 1 2
My current query works just fine in getting me the first two columns but I'm not quite sure how to append it to get this last column, showing the total in 开发者_开发百科each state. Either that or just as good would be State and a column for % lost per state:
State %Lost in State
NY 25%
MD 100%
VA 50%
Here's my current query getting me the first two columns. Hopefully, someone can help me sort out the rest...
SELECT lkuState.StateName as state, Count(lkuState.StateName) AS statecount
FROM lkuState INNER JOIN .........
GROUP BY lkuState.StateName, tblMain.Lost
HAVING ((tblMain.Lost)=false)
In most databases you could use a CASE statement (combined with SUM) to conditionally count the number Lost. But IIRC, Access does not support CASE and uses IIF instead.
SELECT s.StateName, COUNT(*) AS TotalInState,
SUM( IIF(m.Lost = 'yes', 1, 0) ) AS CountLost
FROM tblMain m INNER JOIN lkuState s ON s.StateID = m.StateID
GROUP BY s.StateName
精彩评论