Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi guys,Consider the following dataset:ID|MD|TYPE1|JOHN|A2|JOHN|B3|JOHN|B4|BOB|A5|BOB|A6|BOB|B7|BOB|B8|BOB|BI need to count the number of IDs for each MD and each TYPE like this:MD|A|BJOHN|1|2BOB|2|3I only know how to count everything by MD like this:SELECT MD, COUNT(ID) AS TOTALFROM MY_TABLEGROUP BY MDORDER BY MDThe query above results in:MD|TOTALJOHN|3BOB|5I know there's a trick tot his but can't remember how to accomplish. Your help will be extremely appreciated!Thank you!
James K
Master Smack Fu Yak Hacker
3873 Posts
Posted - 2014-07-14 : 11:30:29
Group by [TYPE] also.
SELECT MD, [TYPE] COUNT(ID) AS TOTALFROM MY_TABLEGROUP BY MD,[TYPE]ORDER BY MD
That is not quite what you want, but now you can pivot the results to get what you want
SELECT * FROM (SELECT MD, [TYPE] COUNT(ID) AS TOTALFROM MY_TABLEGROUP BY MD,[TYPE]) sPIVOT (MAX(Total) FOR [Type] IN ([a],[b]))P ORDER BY MD
sqlslick
Yak Posting Veteran
83 Posts
Posted - 2014-07-14 : 11:57:36
Hi James,I wasn't expecting that but it works like a charm!I should have asked this from the beginning but I'm not really familiar with this PIVOT function. How would I add a third column with the combined total for both A and B, like this:MD|A|B|OVERALLJOHN|1|2|3BOB|2|3|5Thanks in adavanced!
James K
Master Smack Fu Yak Hacker
3873 Posts
Posted - 2014-07-14 : 12:35:23
Probably the easiest is to include that column in the outermost select
SELECT *, [A]+[B] as OVERALL FROM(......
In case there are situations where there is no [A] or no [B], you would want to do
SELECT *, COALESCE([A],0)+COALESCE([B],0) as OVERALL FROM......