2012-10-12 66 views
1

我有下面的數據,我想檢索爲單行。SQL檢索單行

客戶

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 

基於以上數據,我必須顯示如下

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 

請幫我寫這個SQL

問候,

Chaitu

+0

我試過了,但它給了兩行data.i無法將數據放在單行中。同樣的原因,我在這裏發佈我的場景以獲得專家的幫助。 – user1726550

回答

1

您可以使用該聚合函數和CASE聲明:

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 

SQL Fiddle with Demo

根據您的意見,您可以使用以下命令:

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 

SQL Fiddle with Demo

+0

但我仍然得到重複,對不起,我沒有提到其他表我會加入take.two表將根據訂單id equijoin。更新我的問題請檢查。 – user1726550

+0

@ user1726550您請求的最終結果不會使用其他表中的任何內容。你需要這些數據嗎? – Taryn

+0

:客戶表中的訂單ID – user1726550

1

您可以自行加入,然後篩選狀態

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

你可以包括在加入過濾器,如果你有參與多個表格和你想要一個左連接

例如

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'