使用ssms v18。
我正在查看特定销售订单的暂挂类型。
销售订单编号是主id列。
我有4个额外的列用于保持类型。每列都有一个二进制值。
当列的值为1时,我想将任何/所有列名连接到一个字段中。如果没有一列的值为1,那么我希望输入一个字符串"none"。
然后我想创建一个新列,它按顺序id对二进制值求和。
这是我目前掌握的代码。我试过使用UNPIVOT、SUM OVER(PARTITION BY(和STRING_AGG,但我得到了一些重复项。
数据集
order_id | hold_type1 | hold_type2 | >|||||
---|---|---|---|---|---|---|---|
1 | 0 | 0 | tr>2 | 0 | 1 | 0 | 1 |
3 | 1 | 1 | |||||
4 | 1 | 0 | 0 | ||||
5 | 0 | 1 | |||||
6 | 1 | ||||||
7 | 1 | 1 | 0 | //tr>||||
8 | 0 | 1 | <1>|||||
9 | 1 | 0 | <1>|||||
10 | 1 | 0 | 0 |
我们unpivot
并将标志替换为1的type和0的null。那么我们可以只使用group by order_id
,而使用string_agg()
。
select order_id
,case when count(flg) = 0 then 'NONE' else string_agg(flg,', ') end as hold_types
,count(flg) as hold_total
from
(
select order_id
,case when flg = 1 then type end as flg
from t
unpivot (flg for type in(hold_type1, hold_type2, hold_type3, hold_type4)) up
) t
group by order_id
order_id | hold_types | hold_total|
---|---|---|
1 | 无 | 0 |
2 | hold_type2,hold_type4 | <2>|
3 | 保持类型1、保持类型2、保持类型3、保持类型4 | 4 |
4 | 保持类型1 | <1>|
5 | hold_type2,hold_type3 | 2 |
保持类型1,保持类型4 | ||
7 | 保持类型1、保持类型2、保持类型3 | 3|
8 | 保持类型3,保持类型4 | 2 |
9 | 保持类型1、保持类型3、保持类型4 | 3 |
10 | hold_type2 | <1>