到目前为止我的查询:
SELECT CD_no, purchasedate, COUNT(*) mostsales
FROM Sales A
GROUP BY CD_no, purchasedate
HAVING COUNT(*) =
(SELECT MAX(mostsales)
FROM
(SELECT CD_no, purchasedate, COUNT(*) AS mostsales
FROM Sales
GROUP BY CD_no, purchasedate) B
WHERE CD_no = A.CD_no)
到目前为止,我的查询是根据CD_no和购买的输入生成的,查找日期是该特定CD的最大销售额。但是,这仅为每个CD编号返回一个值。但是,CD_no可能在两个不同的日期可能具有完全相同的最大购买量,因此应该根据CD编号显示两个日期。
当前输出:
CD_NO mostsales
1 2011-12-30
2 2012-03-22
3 2012-04-24
期望的输出:
CD_NO mostsales
1 2011-12-30
2 2012-03-22
3 2012-04-24
3 2012-04-22
来自以下输入:
CD_NO purchase_date
1 2011-12-30
1 2011-12-30
1 2011-12-29
1 2011-12-28
2 2012-03-22
2 2012-03-22
2 2012-03-21
3 2012-04-24
3 2012-04-24
3 2012-04-22
3 2012-04-22
3 2012-04-21
答案 0 :(得分:2)
听起来你需要添加一个聚合函数:
SELECT CD_NO, purchase_date, Count(purchase_date) totalSales
FROM Artist
GROUP BY purchase_date
ORDER BY CD_NO
MySQL允许您限制GROUP BY
字段的数量,因此上面仅对purchase_date
进行分组。
在其他RDBMS中,您可以使用子查询:
SELECT a1.CD_NO, a1.purchase_date, a2.TotalSalesByDate
FROM Artist a1
INNER JOIN
(
SELECT count(purchase_date) TotalSalesByDate, purchase_date
FROM Artist
GROUP BY purchase_date
) a2
on a1.purchase_date= a2.purchase_date
ORDER BY a1.CD_NO
击> <击> 撞击>
编辑:根据您的更新,您应该可以使用类似的内容:
SELECT a1.CD_NO, date_format(a1.purchase_date, '%Y-%m-%d') MostSales
FROM Artist a1
INNER JOIN
(
SELECT count(purchase_date) TotalSalesByDate, purchase_date
FROM Artist
GROUP BY purchase_date
) a2
on a1.purchase_date= a2.purchase_date
group by a1.CD_NO, a1.purchase_date
having max(TotalSalesByDate) = (select max(Total) totalsales
from
(
SELECT cd_no, purchase_date, Count(purchase_date) Total
FROM Artist a1
GROUP BY cd_no, purchase_date
) src
where a1.cd_no = src.cd_no
GROUP BY cd_no);
结果:
| CD_NO | MOSTSALES |
----------------------
| 1 | 2011-12-30 |
| 2 | 2012-03-22 |
| 3 | 2012-04-22 |
| 3 | 2012-04-24 |