如果在其他地方被问过,请道歉。我一整天都在寻找Stackoverflow,但还没有找到答案。我正在努力编写查询,以从此示例数据中查找每个州的最高月份销售额。
数据如下所示:
| order_id | month | cust_id | state | prod_id | order_total |
+-----------+--------+----------+--------+----------+--------------+
| 67212 | June | 10001 | ca | 909 | 13 |
| 69090 | June | 10011 | fl | 44 | 76 |
... etc ...
我的查询
SELECT `month`, `state`, SUM(order_total) AS sales
FROM orders GROUP BY `month`, `state`
ORDER BY sales;
| month | state | sales |
+------------+--------+--------+
| September | wy | 435 |
| January | wy | 631 |
... etc ...
返回几百行:每个州每个月的销售总额。我希望它只返回销售额最高的月份,但是对于每个州。不同的州可能会有不同的月份。
此查询
SELECT `state`, MAX(order_sum) as topmonth
FROM (SELECT `state`, SUM(order_total) order_sum FROM orders GROUP BY `month`,`state`)
GROUP BY `state`;
| state | topmonth |
+--------+-----------+
| ca | 119586 |
| ga | 30140 |
返回正确的行数和正确的数据。但我也希望查询给我月份列。无论我尝试使用GROUP BY,我都找不到将结果限制为每个状态一条记录的方法。我已经尝试过PartitionBy但没有成功,并且尝试过连接也没有成功。
TL; DR:一个查询给出了正确的列,但行数太多;另一个查询给了我正确的行数(和正确的数据)但列不足。
非常感谢收到任何有关这项工作的建议。
我使用的是Apache Drill,它显然符合ANSI-SQL标准。希望这没有多大区别 - 我假设解决方案在所有SQL引擎中都是类似的。
答案 0 :(得分:1)
这个应该做的伎俩
SELECT t1.`month`, t1.`state`, t1.`sales`
FROM (
/* this one selects month, state and sales*/
SELECT `month`, `state`, SUM(order_total) AS sales
FROM orders
GROUP BY `month`, `state`
) AS t1
JOIN (
/* this one selects the best value for each state */
SELECT `state`, MAX(sales) AS best_month
FROM (
SELECT `month`, `state`, SUM(order_total) AS sales
FROM orders
GROUP BY `month`, `state`
)
GROUP BY `state`
) AS t2
ON t1.`state` = t2.`state` AND
t1.`sales` = t2.`best_month`
它基本上是您编写的两个查询的组合。
答案 1 :(得分:0)
试试这个:
SELECT `month`, `state`, SUM(order_total) FROM orders WHERE `month` IN
( SELECT TOP 1 t.month FROM ( SELECT `month` AS month, SUM(order_total) order_sum FROM orders GROUP BY `month`
ORDER BY order_sum DESC) t)
GROUP BY `month`, state ;