我有以下数据,我想检索为单行。
客户
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 :(得分: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
根据您的评论,您可以使用以下内容:
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
答案 1 :(得分: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'
如果涉及更多表并且您想要左连接
,则可以在连接中包含过滤器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'