有没有办法合并这些查询,以便我得到一个明确的名称,然后是今天,明天和后天的数量
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
更新
鉴于表
name,qty,delivery_date
芝加哥,1,2011-11-22
纽约,2011年11月2日至2日
芝加哥,3,2011-11-23
我希望有 芝加哥,1,3,8 纽约,1,0,0
答案 0 :(得分: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
答案 1 :(得分: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中的语法相同
答案 2 :(得分: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
答案 3 :(得分: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的更多风格