SQL 查询 - 使用 Case when 语句计算总行数
SQL Queries - Count total of rows with Case when statement
当 [Location] 列匹配特定值时,我想计算以获得正确的行数。 下面是我的 table:
Student | Marks | Location | Date |
---|---|---|---|
Kenn | 66 | UK | 09-01-2022 |
Kenn | 89 | UK | 09-01-2022 |
Kenn | 77 | Canada | 09-01-2022 |
以下SQL查询是我试过的:
SELECT [Student]
,COUNT(CASE WHEN [Location] = 'UK' THEN [Marks] ELSE 0 END) AS UK
,COUNT(CASE WHEN [Location] = 'Canada' THEN [Marks] ELSE 0 END) AS Canada
FROM table_name
GROUP BY [Student]
但是输出是
Student | UK | Canada |
---|---|---|
Kenn | 3 | 3 |
我希望看到的是:
Student | UK | Canada |
---|---|---|
Kenn | 2 | 1 |
请告知我的 SQL 查询是否有任何问题? 谢谢!!
改用总和
SELECT [Student]
,SUM(CASE WHEN [Location] = 'UK' THEN 1 ELSE 0 END) AS UK
,SUM(CASE WHEN [Device] = 'Canada' THEN 1 ELSE 0 END) AS Canada
FROM table_name
GROUP BY [Student]