SQL - 分组 - 将列的值合并为一行?

时间:2018-01-20 15:10:54

标签: sql sql-server sql-server-2016 ssms-2016

(在SSMS2016中工作)我有一张表格如下:

| ORDER_NUMBER | ITEM_CAT| ORDER_QTY | UNALLOCATED|
|--------------|---------|-----------|------------|
|  1           | FLAT    | 2         | 1          |
|  1           | HANG    | 1         | 1          |
|  1           | SHOE    | 2         | 1          |
|  2           | FLAT    | 1         | 1          |
|  2           | FLAT    | 1         | 1          |
|  3           | SHOE    | 1         | 1          |
|  3           | SHOE    | 1         | 1          |
|  3           | SHOE    | 1         | 1          |
|  4           | FLAT    | 1         | 1          |
|  4           | SHOE    | 1         | 1          |
|  4           | FLAT    | 1         | 1          |
|  4           | SHOE    | 1         | 1          |

如果我这样做

SELECT ORDER_NUMBER, ITEM_CAT, SUM(ORDER_QTY) AS 'ORDER_QTY', SUM(UNALLOCATED) AS 'UNALLOCATED' 
FROM TABLEA 
GROUP BY ORDER_NUMBER, ITEM_CAT

我得到以下内容:

| ORDER_NUMBER | ITEM_CAT| ORDER_QTY | UNALLOCATED|
|--------------|---------|-----------|------------|
|  1           | FLAT    | 2         | 1          |
|  1           | HANG    | 1         | 1          |
|  1           | SHOE    | 2         | 1          |
|  2           | FLAT    | 2         | 2          |
|  3           | SHOE    | 3         | 3          |
|  4           | FLAT    | 2         | 2          |
|  4           | SHOE    | 2         | 2          |

理想情况下,我希望每个ORDER_NUMBER只能获得一行,并在同一行中列出唯一的ITEM_CAT值,如下所示:

| ORDER_NUMBER | ITEM_CAT             | ORDER_QTY | UNALLOCATED|
|--------------|----------------------|-----------|------------|
|  1           | FLAT / HANG / SHOE   | 5         | 3          |
|  2           | FLAT                 | 2         | 2          |
|  3           | SHOE                 | 3         | 3          |
|  4           | FLAT / SHOE          | 4         | 4          |

这可以轻松实现吗?

感谢。

1 个答案:

答案 0 :(得分:1)

如果您使用的是SQL Server 2016,则可以使用string_agg()

SELECT ORDER_NUMBER,
       STRING_AGG(ITEM_CAT, ' / ') as ITEM_CATS,
       SUM(ORDER_QTY) AS ORDER_QTY, 
       SUM(UNALLOCATED) AS UNALLOCATED
FROM (SELECT ORDER_NUMBER, ITEM_CAT, SUM(ORDER_QTY) AS ORDER_QTY,
             SUM(UNALLOCATED) AS UNALLOCATED
      FROM TABLEA
      GROUP BY ORDER_NUMBER, ITEM_CAT
     ) a
GROUP BY ORDER_NUMBER;