当另一特定行具有特定元素时,如何使SQL计数特定行

时间:2018-10-17 09:56:20

标签: sql sql-server

表#1

ID     Name    Category
--------------------------------------
1      WASD     cat1
2      QWER     cat1
3      QWER     cat1
4      WASD     cat2
5      WASD     cat2
6      WASD     cat2

我希望能够使用NameCategory并计算表中出现cat1cat2的次数。但是它们都必须与WASD行中的name相对应。

例如,我想要的输出是:

Cat1Amount    Cat2Amount
    1             3

我想要此输出,因为Cat1仅出现一次,这是因为另外2个cat1'sQWER并排。并且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

这个问题是它确实显示了表中cat1cat2出现了多少次,但没有显示WASD出现时它们分别出现多少次。

5 个答案:

答案 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