Declare @YourTable table (sl varchar(10),next int,day int,count int, status varchar(10))
Insert Into @YourTable values
('A' ,1 ,1 ,1 ,'Yes'),
('A' ,1 ,1 ,2 ,'Yes'),
('A' ,1 ,1 ,3 ,'Yes'),
('A' ,1 ,1 ,4 ,'Yes'),
('A' ,1 ,2 ,1 ,'Yes'),
('A' ,1 ,2 ,2 ,'No'),
('A' ,1 ,2 ,3 ,'Yes'),
('A' ,1 ,2 ,4 ,'Yes'),
('A' ,2 ,1 ,1 ,'Yes'),
('A' ,2 ,1 ,2 ,'Yes'),
('A' ,2 ,1 ,3 ,'Yes'),
('A' ,2 ,1 ,4 ,'Yes')
Select sl = IIF(Lag(concat(sl,next,status),1) over (Order by RN)=concat(sl,next,status),'',sl)
,next = IIF(Lag(concat(sl,next,status),1) over (Order by RN)=concat(sl,next,status),'',cast(next as varchar(25)))
,status = IIF(Lag(status,1) over (Order by RN)=status,'',status)
,daylist = concat(day,'-',iif(rowCnt=maxRow,'All',string))
From (
Select *,RN = Row_Number() over (Order by sl,next,day,status desc)
From (
Select sl,Next,Status,Day,rowCnt=count(*)
From @YourTable
Group By sl,Next,Status,Day
) A
Cross Apply (Select maxRow=count(*) From @YourTable Where sl=A.sl and next=A.next and day=A.day) C
Cross Apply (
Select String = Stuff((Select ',' +cast(count as varchar(25))
From @YourTable
Where sl=A.sl and next=A.next and day=A.day and status=A.status
For XML Path ('')),1,1,'')
) B
) A
Order By RN
返回
sl next status daylist
A 1 Yes 1-All
2-1,3,4
A 1 No 2-2
A 2 Yes 1-All
你能解釋一下這個輸出?你在這裏試圖做什麼並不完全清楚。 –
看起來像這樣會在表示層處理(在你的應用程序中),但是不管你想要實現什麼,都是超級混淆。 – scsimon