我试图在SQL Server中创建一个脚本,该脚本将对列下的值进行计数,但是我希望它仍报告未计数的缺失值。
目前,我的分组设置为以下设置,但将结果减半:
select count(ID) as Count, Building, ID
from table
group by Building, ID
我希望我的输出显示每个ID的计数,如果每个ID都没有计数,则显示空值。
Building ID
1234 1
1234 2
4567 3
4567 4
8910 5
0 6
Want the Output To Be:
Building ID Count
1234 1 2
1234 2 2
4567 3 2
4567 4 2
8910 5 1
0 6 0
总人口200,000。我想查看200,000条记录,其中包含每个名称的总计数或空值。运行上述脚本时,每条记录获得1。
示例:如果ID 1的计数为2,而ID 2的计数为2,我希望两个ID都显示为每个ID单独的计数。
答案 0 :(得分:2)
您需要从子查询中获取计数,然后加入该子查询
SELECT
CASE WHEN t1.building is null THEN 0
ELSE t1.building END AS Building,
t1.id,
CASE WHEN t1.building is null THEN 0
ELSE t2.count END AS Count
FROM table t1
JOIN (SELECT building, COUNT(*) as count
FROM table
GROUP BY building) AS t2 ON t2.building = t1.building OR (t2.building is null AND t1.building is null)
答案 1 :(得分:-1)
尝试
select count(name) as Count, ID, Building
from table
group by ID, Building