mySQL query - show most popular item

前端 未结 3 693
渐次进展
渐次进展 2021-02-11 04:53

I need to find the most popular occurrence of an item grouped by date and display the total of all items along with the name of this item. Is something like this possible in a s

3条回答
  •  既然无缘
    2021-02-11 05:17

    This is as close as I could get....

    SELECT DISTINCT p.date, ItemTotalsByDate.Item, DateTotals.Total
        FROM test_popularity p
        INNER JOIN 
    (SELECT date, MAX(cnt) DayMax from
    (SELECT date, item, COUNT(*) cnt
    FROM dbo.test_popularity
    GROUP BY date, item) tbl
    GROUP BY date) MaxesByDate
        ON p. date = MaxesByDate.date
    INNER JOIN 
    (SELECT date, item, COUNT(*) Total FROM dbo.test_popularity
    GROUP BY date, item) ItemTotalsByDate
        ON MaxesByDate.date = ItemTotalsByDate.date AND MaxesByDate.DayMax = ItemTotalsByDate.Total
    INNER JOIN
    (SELECT date, COUNT(*) Total FROM dbo.test_popularity
    GROUP BY date) DateTotals
    ON p.date = DateTotals.date
    

    The only thing this leaves for your PHP to do is only display the first result it finds for a given date. I couldn't figure out a good way to arbitrarily pick one item when it was a tie. Hope this helps.

提交回复
热议问题