我正在使用 MySQL ..
我有一个简单的销售表如下:
o----o----------o-----------o
| id | store_id | logDate |
o----o----------o-----------o
| 1 | 1 | 2015-1-13 |
| 2 | 1 | 2015-1-14 |
| 3 | 2 | 2015-1-11 |
| 4 | 2 | 2015-1-18 |
o----o----------o-----------o
销售产品表
o----o----------o---------o------------o
| id | sale_id | qty | price |
o----o----------o---------o------------o
| 1 | 1 | 1 | 10 |
| 2 | 2 | 1 | 10 |
| 3 | 2 | 1 | 10 |
| 4 | 3 | 1 | 10 |
| 5 | 3 | 1 | 10 |
| 6 | 3 | 1 | 10 |
| 7 | 4 | 1 | 10 |
| 8 | 4 | 1 | 10 |
o----o----------o---------o------------o
预期结果
o-- --------o----------------o---------------------o
| store_id | SUM(price*qty) | Highest Date On |
o-----------o----------------o---------------------o
| 1 | 20 | 2015-1-14 |
| 2 | 30 | 2015-1-11 |
O-----------o----------------o---------------------o
如何达到我的预期效果? 我尝试过以下但是没有按预期工作:
SELECT store_id, MAX(total), highestSingleDateOn
FROM (
SELECT SUM(price * qty) AS total,
DATE(s.logDate) AS highestSingleDateOn, s.store_id AS store_id
FROM sale_product sp JOIN sales s ON s.id = sp.sales_id
GROUP BY DATE(s.logDate), s.store_id
ORDER BY DATE(s.logDate) ASC
) AS result_for_highest_single_day
GROUP BY highestSingleDateOn, store_id
答案 0 :(得分:0)
在MySQL中执行此操作的一种方法是使用多个聚合,然后使用连接。也许更简单的方法是使用变量:
SELECT sd.*
FROM (SELECT sd.*,
(@rn := if(@s = store_id, @rn + 1,
if(@s := store_id, 1, 1)
)
) as rn
FROM (SELECT DATE(s.logDate) AS date, s.store_id, SUM(price * qty) AS total
FROM sale_product sp JOIN sales s ON s.id = sp.sales_id
GROUP BY DATE(s.logDate), s.store_id
ORDER BY s.store_id, total desc
) sd cross join
(SELECT @rn := 0, @s := -1) params
) sd
WHERE rn = 1;
答案 1 :(得分:0)
SELECT store_id, MAX(total), highestSingleDateOn
FROM (
SELECT SUM(price * qty) AS total,
DATE(s.logDate) AS highestSingleDateOn, s.store_id AS store_id
FROM sale_product sp JOIN sales s ON s.id = sp.sales_id
GROUP BY DATE(s.logDate), s.store_id
ORDER BY total DESC
) AS result_for_highest_single_day
GROUP BY store_id
我刚修改了脚本ORDER BY DATE(s.logDate) ASC
>> ORDER BY total DESC
和GROUP BY highestSingleDateOn, store_id
>> GROUP BY store_id
。
*在sql脚本之上,它使用了关于MYSQL的group by
的不稳定特性。
*然后根据Mysql标准,我写了另一个版本的sql脚本。
select table1.*
from
( SELECT SUM(price * qty) AS total,
DATE(s.logDate) AS highestSingleDateOn, s.store_id AS store_id
FROM sale_product sp JOIN sales s ON s.id = sp.sale_id
GROUP BY DATE(s.logDate), s.store_id) as table1
,
(select tmp.store_id,MAX(tmp.total) as max_total from
(SELECT SUM(price * qty) AS total,
DATE(s.logDate) AS highestSingleDateOn, s.store_id AS store_id
FROM sale_product sp JOIN sales s ON s.id = sp.sale_id
GROUP BY DATE(s.logDate), s.store_id ) as tmp group by tmp.store_id) as table2
where table1.store_id = table2.store_id and table1.total=table2.max_total