我有下表(最多可以有15条评论行)
DeliveryNo|LineNo |CommentNo |CommentText
-------- |-------|----------|------------
2214518 |1 |1 |pre SS17 order
2214518 |1 |2 |CHECK DELIVERY DATE
2214518 |1 |3 |02/11/2016
2214518 |1 |4 |For Attention
2214518 |1 |5 |Joe Soaps
需要输出看起来像这样
DeliveryNo| LineNo|Comment1 |Comment2
----------|-------|-------------------|------------
2214518 |1 |pre SS17 order |CHECK DELIVERY DATE
2214518 |1 |02/11/2016 |For Attention
2214518 |1 |Joe Soaps |
答案 0 :(得分:0)
您可以对CASE EXPRESSION
使用条件聚合:
SELECT t.deliveryNo,
t.lineNo,
MAX(CASE WHEN t.CommentNo % 2 = 1 THEN t.commentText END) as comment1,
MAX(CASE WHEN t.CommentNo % 2 = 0 THEN t.commentText END) as comment2
FROM YourTable t
GROUP BY t.deliveryNo,
t.lineNo,
CEIL(t.CommentNo / 2)
答案 1 :(得分:0)
我就是这样做的......
if object_id('tempdb..#Test') is not null drop table #Test
create table #Test (DeliveryNo bigint, Line int, CommentNo int, CommentText nvarchar(100))
insert into #Test(DeliveryNo, Line, CommentNo, CommentText)
values
(2214518 ,1 ,1 ,'pre SS17 order'),
(2214518 ,1 ,2 ,'CHECK DELIVERY DATE'),
(2214518 ,1 ,3 ,'02/11/2016'),
(2214518 ,1 ,4 ,'For Attention'),
(2214518 ,1 ,5 ,'Joe Soaps')
select t1.DeliveryNo,
t1.Line,
t1.CommentText,
t2.CommentText
from #Test t1
left join #Test t2 on t1.CommentNo = t2.CommentNo - 1
where t1.CommentNo % 2 = 1
结果就像你要求的那样
答案 2 :(得分:0)
select
DeliveryNo,
LineNo,
A.CommentText as Comment1,
B.CommentText as Comment2
from table as A left join table as B
on A.DeliveryNo=B.DeliveryNo and A.CommentNo=B.CommentNo-1
where (A.CommentNo mod 2) > 1