SQL Count:如何从其他列的相同值计算列的值

时间:2014-11-16 12:48:06

标签: sql count pivot

对标题感到抱歉。

样品: 我有这张桌子(tblTry):

id | Name | Color
____________________
1  | XYZ  | Black
2  | XYZ  | Black
3  | ASD  | Red
4  | ASD  | White
5  | ASD  | White

这是我想要的输出:

Name | Black | Red | White
__________________________
XYZ  | 2     |  0  |  0
ASD  | 0     |  1  |  2

我有这个sql,但它给了我不同的输出:

select distinct
Name,
(select count(*) from tblTry where Color= 'Black') as Black,
(select count(*) from tblTry where Color= 'Red') as Red,
(select count(*) from tblTry where Color= 'White') as White,
from tblTry
group by Name

以上输出的SQL:

__________________________
Name | Black | Red | White
__________________________
XYZ  | 2     |  1  |  2
ASD  | 2     |  1  |  2

任何人都可以帮助我吗?

由于

1 个答案:

答案 0 :(得分:1)

这是一个支点,有几个解决方案。跨数据库的一般是使用条件聚合:

select name,
       sum(case when Color = 'Black' then 1 else 0 end) as Black,
       sum(case when Color = 'Red' then 1 else 0 end) as Red,
       sum(case when Color = 'White' then 1 else 0 end) as White
from tblTry
group by name;

您的查询存在的问题是需要将计数与每行相关联。您可以使用额外的where条件执行此操作:

(select count(*) from tblTry t2 where t2.Color= 'Black' and t2.name = tblTry.name) as Black,