表#1
ID Name Category
--------------------------------------
1 WASD cat1
2 QWER cat1
3 QWER cat1
4 WASD cat2
5 WASD cat2
6 WASD cat2
我希望能够使用Name
和Category
并计算表中出现cat1
和cat2
的次数。但是它们都必须与WASD
行中的name
相对应。
例如,我想要的输出是:
Cat1Amount Cat2Amount
1 3
我想要此输出,因为Cat1
仅出现一次,这是因为另外2个cat1's
与QWER
并排。并且cat2
出现3次,而WASD出现在cat2
旁边3次。
我当前正在使用它作为查询:
SELECT
Cat1Amount = SUM(CASE WHEN Category='cat1' THEN 1 ELSE 0 END),
Cat2Amount = SUM(CASE WHEN Category='cat2' THEN 1 ELSE 0 END)
FROM
dbo.Example
这个问题是它确实显示了表中cat1
和cat2
出现了多少次,但没有显示WASD
出现时它们分别出现多少次。
答案 0 :(得分:1)
您需要where
子句并进行汇总:
SELECT SUM(CASE WHEN Category = 'cat1' THEN 1 ELSE 0 END),
SUM(CASE WHEN Category = 'cat2' THEN 1 ELSE 0 END)
FROM dbo.Example e
WHERE Name = 'WASD';
答案 1 :(得分:1)
您也可以
SELECT SUM(CASE WHEN Category = 'cat1' AND Name = 'WASD' THEN 1 ELSE 0 END) Cat1Amount,
SUM(CASE WHEN Category = 'cat2' AND Name = 'WASD' THEN 1 ELSE 0 END) Cat2Amount
FROM Tbl
答案 2 :(得分:0)
尝试以下
SELECT name,count(CASE WHEN Category = 'cat1' THEN 1 end) as cat1amount,
count(CASE WHEN Category = 'cat2' THEN 1 END) as cat2amount
FROM dbo.Example e
WHERE Name = 'WASD'
group by name
答案 3 :(得分:0)
SELECT COUNT(Category)
FROM table_name
WHERE name = 'WASD' category = 'cat1';
SELECT COUNT(Category)
FROM table_name
WHERE name = 'WASD' category = 'cat2';
答案 4 :(得分:0)
Select Category, count(ID) as counted
From Table#1 a
where a.Name = 'WASD'
Group by Category
结果将是:
计数类别
cat1 1
cat2 3