SQL拆分字段结果为两个基于值的分组

时间:2015-02-09 09:45:34

标签: sql sql-server

我有一组数据,类似于Microsoft SQL-Server中的以下内容。

|** ITEM **|**              DESCRIPTION                 **|** CODE **| 
1000            Dummy Description for Item 1000               500
1000            Dummy Description for Item 1000               500
1000            Dummy Description for Item 1000               500
1000            Dummy Description for Item 1000               200
1000            Dummy Description for Item 1000               200
1001            Dummy Description for Item 1001               200
1001            Dummy Description for Item 1001               200
1001            Dummy Description for Item 1001               500
1001            Dummy Description for Item 1001               200
1001            Dummy Description for Item 1001               200

我想将ITEM值组合在一起,然后将CODE字段拆分为两个,显示每个项目的CODE = 500和200的计数。会产生类似这样的东西......

|** ITEM **|**              DESCRIPTION                 **|** 500_CODE **| ** 200_CODE **|
    1000            Dummy Description for Item 1000              3              2
    1001            Dummy Description for Item 1001              4              1

2 个答案:

答案 0 :(得分:2)

试试这个:

  select item,
         description,
         sum(case code when 200 then 1 else 0 end) two_hundreds,
         sum(case code when 500 then 1 else 0 end) five_hundreds
    from Table1
group by item, 
         description

您可以在SQLFiddler here

中查看演示

答案 1 :(得分:0)

此查询将为您计算组中的每个代码

SELECT
      [Item],
      [Description],
      [Code],
      COUNT(*) [Count]
  FROM
      [Table1]
  GROUP BY
      [Item],
      [Description],
      [Code];

Fiddle here

如果您真的希望将总计转置为可以使用的列PIVOT

,这可能已满足您的需求
SELECT
      [Item],
      [Description],
      [200] [200_Code]
      [500] [500_Code]
  FROM
(SELECT
      [Item],
      [Description],
      [Code]
  FROM
      [Table1]) [Source]
PIVOT
(
   COUNT([Code]) FOR [Code] IN ([200], [500])
) [Pivot];

See Fiddle