在ssms中,我可以将4个列名转换为一个字符串值(包括当列int值为1时),然后将新列中int值的ttl相加



使用ssms v18。

我正在查看特定销售订单的暂挂类型。

销售订单编号是主id列。

我有4个额外的列用于保持类型。每列都有一个二进制值。

当列的值为1时,我想将任何/所有列名连接到一个字段中。如果没有一列的值为1,那么我希望输入一个字符串"none"。

然后我想创建一个新列,它按顺序id对二进制值求和。

这是我目前掌握的代码。我试过使用UNPIVOT、SUM OVER(PARTITION BY(和STRING_AGG,但我得到了一些重复项。

数据集

>tr>//tr><1><1>
order_id hold_type1 hold_type2
1 0 020101
3 1 1
4 1 0 0
5 0 1
6 1
7 1 1 0
8 0 1
9 1 0
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
hold_total<2><1>3<1>
order_idhold_types
10
2hold_type2,hold_type4
3保持类型1、保持类型2、保持类型3、保持类型44
4保持类型1
5hold_type2,hold_type32
保持类型1,保持类型4
7保持类型1、保持类型2、保持类型3
8保持类型3,保持类型42
9保持类型1、保持类型3、保持类型43
10hold_type2

相关内容

最新更新