2011-12-14 76 views
0

結合數據是否有辦法讓我得到一個不同的名稱,那麼在今天,明天的數量,這些查詢組合,和後天的MySQL從三個查詢

select name, SUM(qty) as qty_today, 0 as qty_tomororow, 0 as qty_om 
from order_item 
where delivery_date = '2011-11-22' 
group by name 
union all 
select name, qty as qty_today, SUM(qty) as qty_tomororow, 0 as qty_om 
from order_item 
where delivery_date = '2011-11-23' 
group by name 
union all 
select name, 0 as qty_today, 0 as qty_tomororow, SUM(qty) as qty_om 
from order_item 
where delivery_date = '2011-11-24' 
group by name 

UPDATE
鑑於表
名稱,數量,DELIVERY_DATE
芝加哥,1,2011-11-22
紐約,2,2011-11-22
芝加哥,3,2011-11-23

我希望
芝加哥,1,3,0
紐約,1,0,0

回答

1

如果你是試圖將它們全部結合在一個數據集中,您可以試試這個,

SELECT name, 
     SUM(CASE WHEN delivery_date = '2011-11-22' THEN qty 
       ELSE 0 END) AS qty_today, 
     SUM(CASE WHEN delivery_date = '2011-11-23' THEN qty 
       ELSE 0 END) AS qty_tomororow, 
     SUM(CASE WHEN delivery_date = '2011-11-24' THEN qty 
       ELSE 0 END) AS qty_om 
from order_item 
where delivery_date between '2011-11-22' and '2011-11-24' 
group by name 

這將在TSQL(MS SQL)的工作,希望它在MySQL的

0

UNION/UNION ALL將這樣的伎倆:

select name, SUM(qty) as qty_today, 0 as qty_tomororow, 0 as qty_om 
from order_item 
where delivery_date = '2011-11-22' 
group by name 
UNION ALL 
select name, qty as qty_today, SUM(qty) as qty_tomororow, 0 as qty_om 
from order_item 
where delivery_date = '2011-11-23' 
group by name 
UNION ALL 
select name, 0 as qty_today, 0 as qty_tomororow, SUM(qty) as qty_om 
from order_item 
where delivery_date = '2011-11-24' 
group by name 
+0

這就是說,看起來你應該`GROUP BY DELIVERY_DATE,name`代替。 – Kenaniah 2011-12-14 20:26:04

1
select name, SUM(qty) as qty_today, 0 as qty_tomororow, 0 as qty_om 
from order_item 
where delivery_date IN ('2011-11-22', '2011-11-23', '2011-11-24') 
group by delivery_date, name 
0
SELECT name, 
     SUM(if (delivery_date = '2011-11-22' , qty , 0)) AS qty_today, 
     SUM(if (delivery_date = '2011-11-23' , qty , 0)) AS qty_tomororow, 
     SUM(if (delivery_date = '2011-11-24' , qty , 0)) AS qty_om 
from order_item group by name 

相同的語法,這是MySQL的更多風格