0

(在 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          |

这很容易实现吗?

谢谢。

4

1 回答 1

2

如果您使用的是 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;
于 2018-01-20T15:13:31.493 回答