我有一个SQL Server查询,可以从多个表中获取数据,目前我处于这种情况:
我得到每个客户和产品的数据。例如,我有5种产品:A,B,C,D,E,那么在PRODUCT IS NULL的那一行还有一个额外的行,但其余各列包含应该用于我的每个产品的值。
我得到这样的数据:
TID Customer PRODUCT VAL1 VAL2 VAL3 VAL4
1 CUST NULL CONTENT1 CONTENT2 CONTENT3 CONTENT4
1 CUST A NULL NULL NULL NULL
1 CUST B NULL NULL NULL NULL
1 CUST C NULL NULL NULL NULL
1 CUST D NULL NULL NULL NULL
1 CUST E NULL NULL NULL NULL
如何将其转换为此输出?
TID Customer PRODUCT VAL1 VAL2 VAL3 VAL4
1 CUST A CONTENT1 CONTENT2 CONTENT3 CONTENT4
1 CUST B CONTENT1 CONTENT2 CONTENT3 CONTENT4
1 CUST C CONTENT1 CONTENT2 CONTENT3 CONTENT4
1 CUST D CONTENT1 CONTENT2 CONTENT3 CONTENT4
1 CUST E CONTENT1 CONTENT2 CONTENT3 CONTENT4
EDIT:
结果我有多个记录,按TID,客户,产品分类
一种方法使用窗口函数:
select t.*
from (select t.tid, t.customer, t.product
max(t.val1) over (partition by t.tid) as val1,
max(t.val2) over (partition by t.tid) as val2,
max(t.val3) over (partition by t.tid) as val3,
max(t.val4) over (partition by t.tid) as val4
from t
) t
where t.product is not null;
另一种方法使用join
:
select tp.id, tp.customer, tp.product,
tv.val1, tv.val2, tv.val3, tv.val4
from t tp join
t tv
on tp.id = tv.id and
tp.product is not null and
tv.product is null;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句