1

以下のデータがあり、単一の行として取得したい。

お客様

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を書くのを手伝ってください

よろしく、

チャトゥ

4

2 に答える 2

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 FiddlewithDemoを参照してください

あなたのコメントに基づいて、あなたは以下を使うことができます:

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 FiddlewithDemoを参照してください

于 2012-10-12T22:20:38.127 に答える
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 フィドルのデモ

より多くのテーブルが含まれていて、左結合が必要な場合は、結合にフィルターを含めることができます

例えば

    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 に答える