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