列
+--------------------------+
| inv_num scn |
+--------------------------+
| MI1001 160008 |
| CI1002 160008 |
| VI1003 160008 |
+--------------------------+
MI 适用于其他商品, CI 适用于货物, VI 适用于货船。
我需要sql结果显示为
+------------------------------------------------+
| scn Misc Cargo Vessel |
+------------------------------------------------+
| 160008 MI1001 CI1002 VI1003 |
+------------------------------------------------+
我是这类新手,所以不确定如何进行查询。
答案 0 :(得分:4)
我会用条件聚合来做到这一点:
select scn,
max(case when inv_num like 'MI%' then inv_num end) as Misc,
max(case when inv_num like 'CI%' then inv_num end) as Cargo,
max(case when inv_num like 'VI%' then inv_num end) as Vessel
from t
group by scn;
答案 1 :(得分:0)
使用Pivot也可以实现
示例数据
Declare @Table1 TABLE
(inv_num varchar(6), scn int)
;
INSERT INTO @Table1
(inv_num, scn)
VALUES
('MI1001', 160008),
('CI1002', 160008),
('VI1003', 160008)
;
脚本
Select scn,[1] AS Misc,[2] As Cargo,[3] As Vessel from (
select
inv_num,
scn,
ROW_NUMBER()OVER(PARTITION BY scn ORDER BY (SELECT NULL))RN
from @Table1)T
PIVOT (MAX(inv_num) FOR RN IN ([1],[2],[3]))PVT