【问题标题】:Pivot row data and count into columns [duplicate]将行数据透视并计入列[重复]
【发布时间】:2021-10-18 03:05:54
【问题描述】:

我有如下两列数据:

Client Type
A Pencil
A Ruler
A Pen
B Pencil
B Ruler
C Pencil
C Pen

我想旋转“类型”并将它们设为列并按“客户”分组。结果如下所示:

Client Count(Pencil) Count(Ruler) Count(Pen)
A 1 1 1
B 1 1 0
C 1 0 1

如何在 SQL Server 上实现这一点?

谢谢

【问题讨论】:

    标签: sql sql-server tsql pivot


    【解决方案1】:

    在 SQL Server 中,您可以将其表示为:

    select client,
           sum(case when type = 'Pencil' then 1 else 0 end) as pencil,
           sum(case when type = 'Ruler' then 1 else 0 end) as ruler,
           sum(case when type = 'Pen' then 1 else 0 end) as pen
    from t
    group by client;
    

    【讨论】:

    • 您忘了您在此之前几小时发布了this answer 吗?
    【解决方案2】:

    请参考MSDN

    SELECT Client, [Pencil], [Ruler], [Pen]
    FROM  
    (
      SELECT Client, Type
      FROM tableName
    ) AS SourceTable  
    PIVOT  
    (  
      count(Type)  
      FOR Type IN ([Pencil], [Ruler], [Pen])  
    ) AS PivotTable;  
    

    【讨论】:

      猜你喜欢
      • 2016-06-18
      • 2019-03-08
      • 1970-01-01
      • 2018-06-15
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多