2014-09-13 48 views
0

我有一個簡單的SQL表四列的數據類型是我想轉動一個SQL表,但不知道如果表是在地擺動我想

Athlete nvarchar(30) 
Mydate date 
Mytime varchar(8) 
Session nvarchar(40) 

Athlete Mydate    Session  Mytime 
Jerry  14/04/2009   200m   00:00:43 
Jerry  14/04/2009   200m   00:00:44 
Jerry  14/04/2009   200m   00:00:38 
Jerry  14/04/2009   200m   00:00:40 
Tom  14/04/2009   200m   00:00:45 
Tom  14/04/2009   200m   00:00:48 
Tom  14/04/2009   200m   00:00:40 
Tom  14/04/2009   200m   00:00:47 
Tom  14/04/2009   200m   00:00:48 

現在,我要的是創建查詢輸出如下

Athlete Mydate  Session  Time1  Time2  Time3  Time4  Time5 Time6 
Jerry  14/04/2009  200m 00:00:43 00:00:44 00:00:38 00:00:40 
Tom  14/04/2009  200m 00:00:40 00:00:45 00:00:48 00:00:40  00:00:47 

任何幫助最讚賞

+0

您正在使用哪種RDBMS? MySQL,PostgreSQL,SQL Server? (並非每個RDBMS都有一個內置的「數據透視」功能)。請添加對應於您的特定RDBMS的標記 – Barranka 2014-09-13 16:23:16

+0

我正在使用Microsoft SQL Server 2012 – JohnyBoy 2014-09-13 16:27:42

+0

'sql'標記引用了一般SQL問題。請務必添加與您正在使用的*特定RDBMS *相對應的標籤(我剛剛爲您完成了該操作,請務必在下次操作時使用;-)) – Barranka 2014-09-13 16:29:16

回答

2

SQL表本質上是無序的,而你似乎並不心目中的排序。儘管你可以使用pivot來做這件事,但我經常只是用條件聚合來解決這個問題。這裏的關鍵是你需要一些時間的號碼。

with t as (
     select t.*, 
      row_number() over (partition by athlete, mydate, session order by (select NULL)) as seqnum 
     from sometable t 
    ) 
select athlete, mydate, session, 
     max(case when seqnum = 1 then time end) as time1, 
     max(case when seqnum = 2 then time end) as time2, 
     max(case when seqnum = 3 then time end) as time3, 
     max(case when seqnum = 4 then time end) as time4, 
     max(case when seqnum = 5 then time end) as time5 
from t 
group by athlete, mydate, session; 
+0

謝謝戈登你是一個明星工作完美 – JohnyBoy 2014-09-13 17:14:54

相關問題