我试图计算一列中的非空行,但它计算所有行,并计算具有字符串“ 1”的列中的行。 我能够为第一列计算具有字符串“ 1”的列中的行,但是在第二列中,它也计算为“ 0”。 我在这里看到了一些文章,但未能解决问题。
SELECT NAME as Agent_Name, COUNT(case when Thumbs_Up= 1 then 1 else null end) as Thumbs_Up,
COUNT(case when No_Solution_Found =1 then 1 else null end) as No_Solution,
COUNT(case when Save is null then 0 else 1 end) as Total_Saves,
FROM table
GROUP BY NAME
表格:
Name | Thumbs_up | No_Solution_Found | Save
Jonathan | 1 | 0 | Saved
Mike | 0 | 1 | Null
Peter | 1 | 0 | Null
Mike | 1 | 0 | Saved
Peter | 0 | 1 | Saved
Mike | 1 | 0 | Saved
Peter | 0 | 1 | Saved
预期结果:
Name | Thumbs_up | No_Solution | Total_Save
Jonathan | 1 | 0 | 1
Mike | 2 | 1 | 2
Peter | 1 | 2 | 2
答案 0 :(得分:3)
尝试使用SUM
而不是COUNT
SELECT NAME as Agent_Name,
SUM(case when Thumbs_Up = 1 then 1 else 0 end) as Thumbs_Up,
SUM(case when No_Solution_Found =1 then 1 else 0 end) as No_Solution,
SUM(case when Save is null then 0 else 1 end) as Total_Saves,
FROM table
GROUP BY NAME
答案 1 :(得分:2)
由于只有Save
列具有NULL
,因此我认为这是您遇到问题的列。
在查询中,您写道:
COUNT(case when Save is null then 0 else 1 end) as Total_Saves,
也就是说,您将NULL
替换为0
,这是一个非null值,因此会被计数。
您大概想写:
COUNT(Save) as Total_Saves
(顺便说一句,查询中as Total_Saves
之后有一个逗号,该逗号不属于该逗号,因为后面没有其他列表达式。)
答案 2 :(得分:1)
尝试以下查询-:
Select
Name,
sum(Thumbs_up),
sum(No_Solution_Found),
count(case when [Save] is not null then 1 else null end) as Total_save
from TABLE
group by Name
SQL Server 2014