我使用MySQL的..SQL - 查找最高的銷售起始日期範圍的單日
我有一個簡單的銷售表如下:
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
這個答案使用MySQL的(錯誤)功能,允許不屬於GROUP BY('highestSingleDateOn'列)的SELECT中的列。 MySQL *顯式警告不要使用此功能(https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html)。還有其他方法可以解決不依賴於*文檔*不穩定的語言特性的問題。 –
@GordonLinoff謝謝你的提醒。我修改了答案。 – Maxy
。 。修改後的版本應該使用顯式的'join',而不是''where''子句中條件的隱式'join'。 –