mySQL query - show most popular item

前端 未结 3 1840
我寻月下人不归
我寻月下人不归 2021-02-11 04:48

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:36

    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.

提交回复
热议问题