【问题标题】:SQL Count: How to count value of a column from the same value of other columnSQL Count:如何从其他列的相同值中计算列的值
【发布时间】:2023-03-11 14:53:01
【问题描述】:

对不起标题。

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

谁能帮帮我?

谢谢

【问题讨论】:

    标签: sql count pivot


    【解决方案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,
    

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 2020-10-24
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      相关资源
      最近更新 更多