希望有人可以帮我解决这个问题。
如果我有样本表:
orderId | itemId | quantity | created
123456 | 1 | 100 | 1478822402
123457 | 1 | 5 | 1478736001
123458 | 2 | 10 | 1478736001
123459 | 2 | 40 | 1478822402
我正在尝试获得一个结果集,它给出了今天和昨天销售的商品数量的总和 - 按项目分组。例如:
item | numSoldToday | numSoldYesterday
1 | 100 | 5
2 | 40 | 10
出于测试目的忽略硬编码时间戳,我可以使用以下方式为今天销售的商品执行此操作:
SELECT item, sum(quantity) as numSoldToday FROM orders
WHERE created >= 1478822400 AND created <= 1478908799
GROUP by item
我可以做到这一点,因为今天只卖了一件与昨天使用子查询:
SELECT sum(quantity) as numSoldToday,
(SELECT (sum(quantity) FROM orders WHERE created >= 1478736000 AND created <= 1478822399 AND item = 1) as numSoldYesterday
FROM orders
WHERE created >= 1478822400 AND created <= 1478908799 AND item = 1
但我似乎无法弄清楚如何将两者结合起来 - 每个项目的分组结果集与今天销售的数字相比,昨天不使用客户端编程语言来获取项目列表和循环通过每一个似乎有点低效的。
我尝试在子查询中放置一个GROUP BY,但这只是给了我一个错误,我无法想到用SQL完成这个操作的最佳方法。
欢迎任何想法! 谢谢: - )
答案 0 :(得分:1)
您可以在聚合的case语句而不是子查询中执行此操作,如下所示;
SELECT
o.item
,SUM(CASE WHEN o.created >= 1478822400 AND o.created <= 1478908799 THEN quantity ELSE 0 END) numSoldToday
,SUM(CASE WHEN o.created >= 1478736000 AND o.created <= 1478822399 THEN quantity ELSE 0 END) numSoldYesterday
FROM orders o
GROUP BY o.item