Counting Items/Rows in DB as Columns Grouped by Another Column

不问归期 提交于 2019-12-11 14:33:55

问题


What I want to do is basically:

 select Type, (Count(*) where Date='')as 10/1, (Count(*) where Date='')as 10/2
 from my table
 group by Type

What I want it to look like is:

 Type   10/1    10/2
 1      5       7
 2      3       1
 3      6       9
 4      1       3
 5      9       8

However, when I try to run a full select within each count column, I end up getting

 Type   10/1    10/2
 1      12      15
 2      12      15
 3      12      15
 4      12      15
 5      12      15

Any suggestions are appreciated. I'm not sure if I will need to run a pivot or not, but I wouldn't think so. Additionally after I can run that for any specific day, I was thinking about trying to put the date into a variable and trying to run the whole thing for a date range, generating columns dynamically for each day its run. I would probably create a new question for that though.


回答1:


Try this;

SELECT TYPE
      ,SUM(CASE WHEN MyDate = '' THEN 1 ELSE 0 END) AS [10/1]
      ,SUM(CASE WHEN MyDate = '' THEN 1 ELSE 0 END) AS [10/2]
FROM MyTable
GROUP BY TYPE


来源:https://stackoverflow.com/questions/21195777/counting-items-rows-in-db-as-columns-grouped-by-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!