sql查询从单行的两个表中获取数据

时间:2012-09-17 13:57:17

标签: asp.net sql-server

(Order Table)
ID  Order_Type  Order_Name  
70  1       1   

(Details Table)
ID  Day    Start_Time   End_Time
70  Monday     17:05:00 18:05:00
70  Tuesday    17:10:00 18:10:00
70  Wednesday  17:15:00 18:15:00
70  Thursday   17:20:00 18:20:00
70  Friday     17:25:00 18:25:00
70  Saturday   17:30:00 18:30:00




 ID  Order_Type Monday_Start_Time  Monday_End_Time  Tuesday_Start_Time  Tuesday_End_Time   
    70  1          17:05:00           18:05:00          17:10:00            18:10:00

我必须在周日开始时间结束时间之前显示上述数据。我应该如何查询

1 个答案:

答案 0 :(得分:3)

您可以使用UNPIVOTPIVOT

select *
from
(
  select id, order_type, order_name,
    day + '_' + col as col,
    val
  from 
  (
    select o.id,
      o.order_type,
      o.order_name,
      d.day,
      d.start_time,
      d.end_time
    from orders o
    inner join details d
      on o.id = d.id
  ) x
  unpivot
  (
    val
    for col in (start_time, end_time)
  ) u
) x1
pivot
(
  min(val)
  for col in ([Monday_start_time], [Monday_end_time], 
              [Tuesday_start_time], [Tuesday_end_time],
              [Wednesday_start_time], [Wednesday_end_time],
              [Thursday_start_time], [Thursday_end_time],
              [Friday_start_time], [Friday_end_time],
              [Saturday_start_time], [Saturday_end_time])
) p

请参阅SQL Fiddle with Demo

如果您不想使用UNPIVOTPIVOT或正在使用没有这些功能的版本,那么您需要执行多个连接:

select o.id,
   o.order_type,
   o.order_name,
   mon.start_time Monday_Start_time,
   mon.end_time Monday_End_time,
   tues.start_time Tuesday_Start_time,
   tues.end_time Tuesday_End_time,
   wed.start_time Wednesday_Start_time,
   wed.end_time Wednesday_End_time,
   thur.start_time Thursday_Start_time,
   thur.end_time Thursday_End_time,
   fri.start_time Friday_Start_time,
   fri.end_time Friday_End_time,
   sat.start_time Saturday_Start_time,
   sat.end_time Saturday_End_time
from orders o
left join details mon
  on o.id = mon.id
  and mon.day = 'Monday'
left join details tues
  on o.id = tues.id
  and tues.day = 'tuesday'
left join details wed
  on o.id = wed.id
  and wed.day = 'wednesday'
left join details thur
  on o.id = thur.id
  and thur.day = 'thursday'
left join details fri
  on o.id = fri.id
  and fri.day = 'friday'
left join details sat
  on o.id = sat.id
  and sat.day = 'saturday'

请参阅SQL Fiddle with Demo