2012-07-31 107 views
1

我是SQL新手,請幫助我如何將它轉換爲水平數據?例如:用於將垂直數據轉換爲水平數據的SQL 2008腳本

(舊)

No  Mchn EnNo  Name  DateTime 
00001 1  01110037 Juan  2012/07/16 08:00:18 
00002 1  01110037 Juan  2012/07/16 12:02:23 
00003 1  01110037 Juan  2012/07/16 12:42:23 
00004 1  01110037 Juan  2012/07/16 18:42:23 
00005 1  01110038 Robert 2012/07/16 08:00:18 
00006 1  01110038 Robert 2012/07/16 12:02:23 
00007 1  01110038 Robert 2012/07/16 12:42:23 
00008 1  01110038 Robert 2012/07/16 18:42:23 

結果,我想展示..

(新)

EnNo   Name Date   TimeIn  BrkIn  BrkOut  TimeOut 
01110037  Juan 2012/07/16 08:00:18 12:02:23 12:42:23 18:42:23 
01110038  Robert 2012/07/16 08:00:18 12:02:23 12:42:23 18:42:23 

回答

2

你可以嘗試這樣的事情:

select 
EnNo, Name, convert(varchar(10),DateTime,101) date, 

-- TimeIn 
convert(varchar(8),min(DateTime),114) TimeIn, 

-- BreakIn 
(select convert(varchar(8),max(DateTime),114) 
     from (select top 2 DateTime from oldTable where EnNo = t1.EnNo and 
      CONVERT(varchar(10),DateTime,101) = CONVERT(varchar(10),t1.DateTime,101))t2 
) BreakIn, 

-- BreakOut 
(select convert(varchar(8),max(DateTime),114) 
     from (select top 3 DateTime from oldTable where EnNo = t1.EnNo and 
      CONVERT(varchar(10),DateTime,101) = CONVERT(varchar(10),t1.DateTime,101))t3 
) BreakOut, 

-- TimeOut 
convert(varchar(8),max(DateTime),114) TimeOut 
from oldTable t1 
group by EnNo,Name,convert(varchar(10),DateTime,101) 
+1

怎麼樣BRKIN,BRKOUT? – 2012-07-31 12:53:24

+0

你可以使用「選擇頂部」。看到我編輯的查詢。 – 2012-08-01 06:02:11

2

這應該給你所有你想要的字段:

select * 
from 
(
    select 
     enno 
     , name 
     , cast(dt as date) dy 
     , CONVERT(char(8), dt, 114) as tm 
     , Case row_number() over(partition by enno order by dt) 
      when 1 then 'timein' 
      when 2 then 'brkin' 
      when 3 then 'brkout' 
      when 4 then 'timeout' END as BreakType 
    from t 
) x 
pivot 
(
    min(tm) 
    for breaktype in ([timein], [brkin], [brkout], [timeout]) 
) p 

SQL Fiddle with Demo

+0

** + 1 **使用sql小提琴 – 2012-08-01 06:47:53