I have a table with an id field (int) and a bit flag. example below
id flag
1 true
1 true
1 false
1 true
2 true
2 false
I am looking for a query that will provide me the following results if possible
id true false
1 3 1
2 1 1
Any and all help is appreciated.
My efforts so far aren't worth sharing. I am looking for completely new approaches.
Thanks a ton
Use something like this:
Code Snippet
DECLARE @.MyTable table
( ID int,
Flag smallint
)
INSERT INTO @.MyTable VALUES ( 1, 1 )
INSERT INTO @.MyTable VALUES ( 1, 1 )
INSERT INTO @.MyTable VALUES ( 1, 0 )
INSERT INTO @.MyTable VALUES ( 1, 1 )
INSERT INTO @.MyTable VALUES ( 2, 1 )
INSERT INTO @.MyTable VALUES ( 2, 0 )
SELECT
[ID],
True = sum( CASE Flag WHEN 1 THEN 1 ELSE 0 END ),
False = sum ( CASE Flag WHEN 0 THEN 1 ELSE 0 END )
FROM @.MyTable
GROUP BY [ID]
ID True False
-- -- --
1 3 1
2 1 1
No comments:
Post a Comment