繁体   English   中英

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

[英]SQL Count: How to count value of a column from the same value of other column

抱歉,标题。

示例:我有这张桌子(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

谁能帮我?

谢谢

这是一个枢纽,有几种解决方案。 跨数据库的普遍做法是使用条件聚合:

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,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM