哪张CD在去年7月到7月间销售额增加了

时间:2012-12-02 00:33:30

标签: mysql database

该销售的价值,因为在一个日期可能有很多销售,并且会有很多行。

但是我不知道我怎么能这样做。

到目前为止,我有:

SELECT cd_no
FROM sales

我问我认为是在子查询选择中,别名'm'返回'NULL'

1 个答案:

答案 0 :(得分:3)

您可以按CD_NO分组并计算行数来计算每张CD的总销售数量:

SELECT CD_NO, COUNT(*) AS purchases
FROM Sales
GROUP BY CD_NO

您可以在特定日期范围内获取每张CD的销售数量(因为<date condition>在True时为1,在False时为0):

SELECT CD_NO, SUM(<date condition>) AS purchases
FROM Sales
GROUP BY CD_NO

2012年7月,您可以使用purchasedate BETWEEN '2012-07-01' AND '2012-07-31'YEAR(purchasedate) = 2012 AND MONTH(purchasedate) = 7以及其他选项。

比较两个日期范围

SELECT
    CD_NO,
    SUM(purchasedate BETWEEN '2012-07-01' AND '2012-07-31') AS a,
    SUM(purchasedate BETWEEN '2011-07-01' AND '2011-07-31') AS b
FROM Sales
GROUP BY CD_NO

最后,选择行数增加15%的行......

SELECT CD_NO
FROM (
    SELECT
        CD_NO,
        SUM(purchasedate BETWEEN '2012-07-01' AND '2012-07-31') AS a,
        SUM(purchasedate BETWEEN '2011-07-01' AND '2011-07-31') AS b
    FROM Sales
    GROUP BY CD_NO) AS t
WHERE t.a > 1.15 * t.b

或简单地说:

SELECT CD_NO
FROM Sales
GROUP BY CD_NO
HAVING       SUM(purchasedate BETWEEN '2012-07-01' AND '2012-07-31') 
     > 1.15 * SUM(purchasedate BETWEEN '2011-07-01' AND '2011-07-31') ;