2012-09-17 155 views
0
(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 

我必須表現出類似上面的數據,直到週日開始時間結束time.How應該是我的查詢SQL查詢從兩個表中獲取數據單列

+0

加入訂單表7人加入到Details表。 –

+0

如何......應該是查詢 – lax

+0

下面的一個會工作 – Pushpendra

回答

3

您可以使用UNPIVOT和這個PIVOT

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或與D A版本正在OES沒有這些功能,那麼你就需要執行多個聯接:

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

相關問題