MySQL选择另一行的顶行分组

时间:2016-10-14 01:07:29

标签: mysql group-by

我有一张销售表,我希望在过去3个月内让每个成员最常购物。以下查询将获取每个商店的每个成员,但我希望每个成员只有一个商店。

SELECT member_id, store_id, COUNT(DISTINCT docket) as docket_count, SUM(dollar_amount) as dollars
FROM sales
WHERE TIMESTAMPDIFF(MONTH, sale_date, CURDATE()) < 3
GROUP BY member_id, store_id
ORDER BY member_id, docket_count DESC, dollars DESC

或者获得单个会员的顶级商店

SELECT store_id, COUNT(DISTINCT docket) as docket_count, SUM(dollar_amount) as dollars
FROM sales
WHERE TIMESTAMPDIFF(MONTH, sale_date, CURDATE()) < 3
AND member_id = 1
GROUP BY store_id
ORDER BY docket_count DESC, dollars DESC

1 个答案:

答案 0 :(得分:1)

这很棘手。在MySQL中,使用group_concat() / substring_index()技巧最简单:

SELECT member_id,
       SUBSTRING_INDEX(GROUP_CONCAT(store_id ORDER BY docket_count DESC  dollars DESC), ',', 1) as Most_Common_Store
FROM (SELECT member_id, store_id, COUNT(DISTINCT docket) as docket_count, 
             SUM(dollar_amount) as dollars
      FROM sales
      WHERE sale_date >= CURDATE() - interval 3 month
      GROUP BY member_id, store_id
     ) ms
GROUP BY member_id;