2017-05-27 57 views
0

這裏的數據:SQL爲每個組查找列順序由另一列

studentid,state,score,date,modno,transactionno 
1,IL,10,20170101,0,0 
1,VA,20,20170102,1,1 
1,FL,30,20170103,2,2 
2,VA,40,20170101,0,0 
2,IL,50,20170102,1,1 
2,IN,60,20170103,2,2 

這裏的輸出應該是這樣:

studentid,state,score,date 
1,IL,20,20170101 
2,VA,60,20170102 

所以基本上我們通過studentid要組。

根據最低的modno和transactionno查找第一個狀態。

根據最高的modno和transactionno查找第一個分數。

select studentid, 
     (select top 1 state from student s1 where s.studentid = s1.studentid order by modno, transactionno) as state, 
     (select top 1 score from student s1 where s.studentid = s1.studentid order by modno desc, transactionno desc) as score, 
     (select top 1 date from student s1 where s.studentid = s1.studentid order by modno, transactionno) as date 
from student s 
group by studentid 

以上是我在SQL 2008中的查詢。是否有其他方法來編寫此查詢以獲得更好的性能?當處理大型數據集並且每組拉出兩個以上的列時,它真的會顯示出來。

+0

爲什麼一個'studentid'列有在'student'表中的多個行? –

+0

我不理解輸出。應該使用什麼*日期*爲什麼20爲id - 1?它不應該是30嗎? – Parfait

回答

0

我想我會用條件彙總處理這個:

select studentid, 
     max(case when seqnum_asc = 1 then state end) as state, 
     max(case when seqnum_desc = 1 then score end) as score, 
     max(case when seqnum_asc = 1 then date end) as date 
from (select s.*, 
      row_number() over (partition by studentid order by modno, transactionno) as seqnum_asc, 
      row_number() over (partition by studentid order by modno desc, transactionno desc) as seqnum_desc 
     from student s 
    ) s 
group by studentid; 
0

猜猜你的輸出是不正確的,或者我們沒有帶在你的輸出unserdtood日期部分。

試試這個其他的樣本數據,讓我們知道,

declare @t table(studentid int,states varchar(20), score int 
,dates date,modno int,transactionno int) 

insert into @t VALUES 
(1,'IL',10,'20170101',0,0) 
,(1,'VA',20,'20170102',1,1) 
,(1,'FL',30,'20170103',2,2) 
,(2,'VA',40,'20170101',0,0) 
,(2,'IL',50,'20170102',1,1) 
,(2,'IN',60,'20170103',2,2) 
;with CTE as 
(
select studentid from @t 
group by studentid 
) 
SELECT t.studentid,ca.states,ca1.score,ca.dates 
from CTE t 
cross apply(select top 1 t1.states,t1.dates from @t t1 
where t.studentid=t1.studentid 
order by modno,transactionno)ca 
cross apply(select top 1 t1.score from @t t1 
where t.studentid=t1.studentid 
order by modno desc,transactionno desc)ca1 
--cross apply(select top 1 t1.dates from @t t1 
--where t.studentid=t1.studentid 
--order by modno ,transactionno )ca2