根据结果,我有一列具有不同的值。 我想用修复列返回一行。
列输出如下:
Group | Item
--------------
G1 | 1
G1 | 2
G2 | 3
我想输出为:
Group | Item1 | Item2 | Item3
-----------------------------
G1 | 1 | 2 | N/A
G2 | 3 | N/A | N/A
请帮助..
提前致谢...
答案 0 :(得分:3)
因为每个组最多可以有三个项目,所以我会使用PIVOT operator:
DECLARE @Test TABLE
(
RowID INT IDENTITY(1,1) PRIMARY KEY
,[Group]VARCHAR(10) NOT NULL
,Item INT NOT NULL
,UNIQUE ([Group], Item)
);
INSERT @Test VALUES ('G1', 1);
INSERT @Test VALUES ('G1', 2);
INSERT @Test VALUES ('G2', 3);
WITH PivotSource
AS
(
SELECT t.[Group], t.Item
,ROW_NUMBER() OVER(PARTITION BY t.[Group] ORDER BY t.RowID) RowNumber
FROM @Test t
)
SELECT pvt.[Group]
,Item1 = ISNULL( CONVERT(VARCHAR(11), pvt.[1]) , 'N/A')
,Item2 = ISNULL( CONVERT(VARCHAR(11), pvt.[2]) , 'N/A')
,Item3 = ISNULL( CONVERT(VARCHAR(11), pvt.[3]) , 'N/A')
FROM PivotSource src
PIVOT ( MAX(src.Item) FOR src.RowNumber IN ([1], [2], [3]) ) pvt;
结果:
Group Item1 Item2 Item3
---------- ----------- ----------- -----------
G1 1 2 N/A
G2 3 N/A N/A
答案 1 :(得分:1)
我想这样的事情会奏效:
SELECT t1.[Group], t1.Item, t2.Item, t3.Item
from tbl t1, tbl t2, tbl t3
where t1.[Group] = t2.[Group] and t1.[Group] = t3.[Group]
and t1.Item < t2.Item and t2.Item < t3.Item
and t1.[Group] in (select [Group] from tbl group by [Group] having COUNT(*) = 3)
union
SELECT t1.[Group], t1.Item, t2.Item, NULL
from tbl t1, tbl t2
where t1.[Group] = t2.[Group]
and t1.Item < t2.Item
and t1.[Group] in
(select [Group] from tbl group by [Group] having COUNT(*) = 2)
union
select tbl.[Group], tbl.Item, NULL, NULL
from tbl
where [Group] in (select [Group] from tbl group by [Group] having COUNT(*) = 1)
答案 2 :(得分:0)
由于您拥有固定数量的输出列,因此您可以使用ROW_NUMBER()
和over (partition by ... order by ...)
执行一些操作。
select child1.[Group], child1.Item as Item1, child2.Item as Item2, child3.Item as Item3 from
(select [Group], Item from
(select [Group], Item, (ROW_NUMBER() over(partition by [group] order by item)) as rownum from GroupTable) as child1_inner
where child1_inner.rownum = 1) as child1
left outer join
(select [Group], Item from
(select [Group], Item, (ROW_NUMBER() over(partition by [group] order by item)) as rownum from GroupTable) as child2_inner
where child2_inner.rownum = 2) as child2
on child1.[Group] = child2.[Group]
left outer join
(select [Group], Item from
(select [Group], Item, (ROW_NUMBER() over(partition by [group] order by item)) as rownum from GroupTable) as child3_inner
where child3_inner.rownum = 3) as child3
on child1.[Group] = child3.[Group]
这会返回null
而不是N/A
,但您可以使用COALESCE
进行修复。