lax
lax

Reputation: 518

sql query get data from two table in single row

(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

I have to show data like above till sunday start time end time.How should be my query

Upvotes: 0

Views: 385

Answers (1)

Taryn
Taryn

Reputation: 247730

You can use an UNPIVOT and a PIVOT for this:

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

see SQL Fiddle with Demo

If you didn't want to use the UNPIVOT and PIVOT or are working with a version that does not have those functions, then you would need to perform multiple joins:

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'

see SQL Fiddle with Demo

Upvotes: 3

Related Questions