分组和计算多列SQL的更好方法

时间:2019-05-08 16:01:57

标签: sql sql-server group-by count

I have a survey table that shows the answers that people have taken once 
a month when they enter a contest. I'm trying to find a better way to 
have the sum of  people who answer "Just Me ,My Spuse/Partner" and 
another sum of people who people who answer  Children, 0-5, 6-12,13-17

This is the table called "Survey" that is provided:
User    JustMe      Children 0-5      Children 6-12    Myspouse/partner
  5      N              N               N                  N                           
  5      N              N               N                  N
  4      N              N               N                  N
  4      N              N               N                  N
 24      N              N               N                  N
 24      N              N               N                  N
 12      N              N               N                  N
 12     Just Me         N               N              Myspousepartner           
 46     Just Me         N        Children 6-12 years   Mypousepartner
 46     Just Me         N        Children 6-12 years   Mypousepartner

我只希望有一个像这样的桌子

我希望我的表格能反映出孩子年龄段和justme / partner的总和

I hope my output will be like this:
Children    JustMe/Partner
4045         1200 


  * I tried this code:
    SELECT 
    Children_13_17_years,Children_6_12_years,
    TotalSubjects= Count(*) Over (partition by Children_13_17_years),
    TotalSub= Count(*) Over (partition by Children_6_12_years)

1 个答案:

答案 0 :(得分:1)

尝试根据案例陈述选择总和。如果满足case语句,则总和增加1。

select * 
from Application 
where 
    @ChangeStatus is null OR
    (@ChangeStatus = 'Y' AND Changes like '%') OR
    (@ChangeStatus = 'N' AND Changes is null)

**您可能必须更改方括号中的列名称,别名和表名称。如果您在数据库中使用SELECT SUM(CASE WHEN [Children 0-5] IS NOT NULL OR [Children 6-12] IS NOT NULL OR [Children 13-17] IS NOT NULL THEN 1 ELSE 0 END) as '[Children]', SUM(CASE WHEN [JustMe] IS NOT NULL OR [Myspouse/partner] IS NOT NULL THEN 1 ELSE 0 END) as '[JustMe/Partner]' FROM [TableName] 字符而不是null,则可能还需要将case语句更改为col != 'N'