计算SQL中的所有值,如果没有任何计数,则返回0

时间:2018-06-19 16:03:34

标签: sql sql-server

Select State, City, Count(Student) as StudentCount
from Table1
where (State = 'Uttar Pradesh' 
       and City in ('Noida', 'Lucknow', 'Agra', 'Kanpur', 'Greater Noida'))
group by State, City

例如,我需要学生的人数,并且还想要包括所有没有学生的城市。

我需要以下输出

State           City           StudentCount
---------------------------------------------
Uttar Pradesh   Noida            20
Uttar Pradesh   Lucknow          30
Uttar Pradesh   Agra              0
Uttar Pradesh   Kanpur            0
Uttar Pradesh   Greater Noida    40

但是我现在正在得到

State           City           StudentCount
-------------------------------------------
Uttar Pradesh   Noida            20
Uttar Pradesh   Lucknow          30
Uttar Pradesh   Greater Noida    40

它跳过了没有计数的两行。

2 个答案:

答案 0 :(得分:2)

您需要从要计算的城市列表开始。然后,您可以将其LEFT JOIN与实际数据进行汇总。当您按州进行查询和过滤时,将消除没有城市记录的行。您要保留这些。

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=147d6d6cf823d30b139458cbb220cc94

设置

CREATE TABLE table1 (state varchar(20), city varchar(20), studentID int) ;

INSERT INTO table1 (state, city, studentID)
VALUES 
    ('Uttar Pradesh','Noida',1)
  , ('Uttar Pradesh','Noida',2)
  , ('Uttar Pradesh','Noida',3)
  , ('Uttar Pradesh','Lucknow',4)
  , ('Uttar Pradesh','Lucknow',5)
  , ('Uttar Pradesh','Greater Noida ',6)
  , ('Uttar Pradesh','Greater Noida ',7)
  , ('Uttar Pradesh','Greater Noida ',8)
  , ('Uttar Pradesh','Greater Noida ',9)
;
GO

QUERY (使用CTE)。

; WITH cities AS (
  SELECT 'Uttar Pradesh' AS state, 'Noida' AS city UNION ALL
  SELECT 'Uttar Pradesh' AS state, 'Lucknow' UNION ALL
  SELECT 'Uttar Pradesh' AS state, 'Agra' UNION ALL
  SELECT 'Uttar Pradesh' AS state, 'Kanpur' UNION ALL
  SELECT 'Uttar Pradesh' AS state, 'Greater Noida'
)
SELECT table1.State, cities.city, count(table1.studentID) AS thecount
FROM cities 
LEFT OUTER JOIN table1 ON cities.city = table1.city
    AND table1.State = 'Uttar Pradesh'
GROUP BY cities.city, table1.State
;

GO
State         | city          | thecount
:------------ | :------------ | -------:
Uttar Pradesh | Noida         |        3
Uttar Pradesh | Lucknow       |        2
null          | Agra          |        0
null          | Kanpur        |        0
Uttar Pradesh | Greater Noida |        4

db <>提琴here

答案 1 :(得分:0)

您无需使用cte,可以直接将其表示为:

select t1.State, t.City, count(t1.Student) as Student
from ( values ('Noida'), ('Lucknow'), ('Agra'), 
              ('Kanpur'), ('Greater Noida') 
     ) t(City) left join 
     Table1 t1
     on t1.city = t.city and t1.State = 'Uttar Pradesh'
group by t1.State, t.City