1

I have below data, I want to retrieve as single row.

Customer

customer id    customer name  order id

1               Jhon           1

2                philips       1

Order id   order name  order status   order status time
----------------------------------------------------------------    
   1       iphone      delivered      20121011 12:10:01
   1       iphone      cancelled      20121011 14:30:00  

Based on above data, I have to display as below

order id  order name  order status(D)  order status(C) order status(c) time  order status(D) time
------------------------------------------------------------------------------------------------    
   1      iphone      delivered        cancelled       20121011 14:30:00     20121011 12:10:01

Please help me to write this SQL

Regards,

Chaitu

4

2 回答 2

1

You can use an aggregate function and a CASE statement for this:

select orderid,
  ordername,
  max(case when orderstatus = 'delivered' then orderstatus end) OrderStatusD,
  max(case when orderstatus = 'cancelled' then orderstatus end) OrderStatusC,
  max(case when orderstatus = 'delivered' then orderstatustime end) OrderStatusDTime,
  max(case when orderstatus = 'cancelled' then orderstatustime end) OrderStatusCTime
from yourtable
group by orderid, ordername

See SQL Fiddle with Demo

Based on your comments, you can use the following:

select * 
from 
(
  select c.*, 
    row_number() over(partition by orderid order by customerid) rn
  from customer c
) c
inner join
(
  select orderid,
    ordername,
    max(case when orderstatus = 'delivered' then orderstatus end) OrderStatusD,
    max(case when orderstatus = 'cancelled' then orderstatus end) OrderStatusC,
    max(case when orderstatus = 'delivered' then orderstatustime end) OrderStatusDTime,
    max(case when orderstatus = 'cancelled' then orderstatustime end) OrderStatusCTime
  from yourtable
  group by orderid, ordername
) table1
  on c.orderid = table1.orderid
  and c.rn = 1

See SQL Fiddle with Demo

于 2012-10-12T22:20:38.127 回答
1

You can do a self join and then filter for the status

select 
  yt_d.orderid,
  yt_d.ordername,
  yt_d.orderstatus orderstatusD,
  yt_c.orderstatus orderstatusC,
  yt_d.orderstatustime orderstatustimeD,
  yt_c.orderstatustime orderstatustimeC 


from yourtable yt_d
     INNER JOIN yourtable yt_c
      ON yt_d.orderid = yt_c.orderID

where
  yt_d.orderstatus = 'delivered' 
  and yt_c.orderstatus = 'cancelled'

SQL Fiddle demo

You could include the filters in the join if you had more tables involved and you wanted a left join

e.g.

    order o
    LEFT JOIN order_status d
      on o.orderID = d.orderID
        and d.Status = 'delivered'


    LEFT JOIN order_status c
      on o.orderID = c.orderID
        and c.Status = 'canceled'
于 2012-10-12T22:48:12.523 回答