我有一个名为'Sales`的大表,有这些区域
Time | Product | amount | customerid
Date1 | Product1 | 2 | 2
Date1 | Product2 | 5 | 3
Date1 | Product1 | 6 | 3
Date1 | Product4 | 1 | 3
Date2 | Product1 | 2 | 1
Date2 | Product1 | 2 | 4
Date2 | Product3 | 3 | 4
Date2 | Product3 | 3 | 1
现在,我希望每天都能获得最受欢迎的产品。
SELECT Time,
Product,
SUM(amount) AS Total
FROM Sales
GROUP BY Time, Product
给我以下
Time | Product | total
Date1 | Product1 | 8
Date1 | Product2 | 5
Date1 | Product4 | 1
Date2 | Product1 | 4
Date2 | Product4 | 6
我必须改变我的查询,才能获得每天最畅销的产品?
编辑:非常感谢您的解决方案,但它不起作用。 我想总结一下,哪个产品是每天最畅销的产品
Time | Product | total
Date1 | Product1 | 8
Date2 | Product4 | 6
答案 0 :(得分:3)
尝试此查询。 Rank功能的实现在不同的DB中是不同的。
SELECT TIME, PRODUCT
FROM (
SELECT TIME, PRODUCT, RANK() OVER(ORDER BY SUM_AMOUNT) AS SELECT_TOP
FROM
(
(
SELECT
TIME
, PRODUCT
, SUM(AMOUNT) AS SUM_AMOUNT
FROM Sales
GROUP BY TIME, PRODUCT ) TBL1 ) TBL2
WHERE
SELECT_TOP = 1
答案 1 :(得分:1)
SELECT Time, Product, SUM(amount) AS Total FROM Sales GROUP BY Time, Product order by sum(amount) DESC;
答案 2 :(得分:1)
SELECT Time, Product, SUM(amount) AS Total FROM Sales GROUP BY Time, Product ORDER BY Total DESC limit 1
我使用ORDER BY Total DESC
按降序对Total
列进行排序,以便Total
列的最大值位于顶部。因此,我只需按limit 1
答案 3 :(得分:1)
查询:
SELECT
Time, Product, SUM(amount) AS Total
FROM Sales
GROUP BY Time, Product
ORDER BY time Desc, Total DESC