销售,因为一个日期可以有很多销售,并且会有很多行。
但是我不确定我该怎么做。
到目前为止,我有:
SELECT cd_no
FROM sales
我认为是在子查询选择中,别名“m”返回“NULL”
您可以通过按 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') ;