日期:2014-05-18  浏览次数:20561 次

急。。。新手求解答
Table1
Name Time
张三 0745
张三 0945
张三 1210
张三 1520
张三 1750

Table2
Name Time1 Time2 Time3 Time4
张三 0745 0945 1210 1520

我现在要把Table1的内容存到Table2. Time1,Time2,Time3,Time4按照先后顺序排列,超过4个的不取


------解决方案--------------------
SQL code
select
  name,
  max(case px when 1 then Time else 0 end) as time1,
  max(case px when 2 then Time else 0 end) as time2,
  max(case px when 3 then Time else 0 end) as time3,
  max(case px when 4 then Time else 0 end) as time4
from
  (select px=row_number()over(order by getdate()),* from tb)t
group by
  name

------解决方案--------------------
SQL code
;with cte as(
select *,row=ROW_NUMBER()over(PARTITION by [name] order by [time]) from  Table1 
)

select [name],
 max(case row when 1 then [time] else 0 end) as time1,
  max(case row when 2 then [time] else 0 end) as time2,
  max(case row when 3 then [time] else 0 end) as time3,
  max(case row when 4 then [time] else 0 end) as time4

 from cte group by [name]

name                                               time1       time2       time3       time4
-------------------------------------------------- ----------- ----------- ----------- -----------
张三                                                 745         945         1210        1520

(1 行受影响)