0

My query so far:

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)

My query so far generates from an input of CD_no's and purchase's, finds date had the most sales for that specific CD. However this only returns one value for each CD number. However there may be a possibility that a CD_no may have the exact same maximal purchases on two different dates, and therefore should display both dates against the CD number.

Current output:

CD_NO           mostsales
1             2011-12-30
2             2012-03-22
3             2012-04-24

Desired output:

CD_NO           mostsales
1             2011-12-30
2             2012-03-22
3             2012-04-24
3             2012-04-22

From the following input:

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
4

1 回答 1

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);

请参阅带有演示的 SQL Fiddle

结果:

| CD_NO |  MOSTSALES |
----------------------
|     1 | 2011-12-30 |
|     2 | 2012-03-22 |
|     3 | 2012-04-22 |
|     3 | 2012-04-24 |
于 2012-11-28T15:44:24.157 回答