(在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 |
这可以轻松实现吗?
感谢。
答案 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;