【问题标题】:Counting values within the same row in SQL Server在 SQL Server 中计算同一行中的值
【发布时间】:2020-09-24 09:09:16
【问题描述】:

我的 SQL Server 问题如下:假设我们有客户,我们希望根据 0 到 2 的 4 个类别(Score_1...Score_4)对它们进行评分。我有一张下表:

我希望我的代码做的是计算我的每个客户收到的 0、1 和 2 值的数量。我想得到的结果表是这样的:

所以client_1得到两个0分,一个1分和一个2分,client_2得到一个0分,一个1分和两个2分。有什么建议么?提前致谢!

【问题讨论】:

    标签: sql sql-server count pivot unpivot


    【解决方案1】:

    您可以取消透视,然后进行条件聚合:

    select t.id, 
        sum(case when x.score = 0 then 1 else 0 end) cnt_0,
        sum(case when x.score = 1 then 1 else 0 end) cnt_1,
        sum(case when x.score = 2 then 1 else 0 end) cnt_2
    from mytable t
    cross apply (values (score_1), (score_2), (score_3), (score_4)) x(score)
    group by t.id
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 2016-01-10
      相关资源
      最近更新 更多