最常见的值+每个

时间:2017-09-20 12:16:02

标签: mysql sql database

我有以下订单表:

  

Client_name |产品
Megane |#768_Samsung
Megane |#310_Apple
  梅甘娜|#659_Samsung
Victor |#890_Apple

我希望为每个客户看到他们最买的品牌+他们购买品牌的时间。 所以对于这张桌子,我喜欢这个结果:

  

Client_Name | Favourite_brand | Order_number
梅根|三星| 2
  维克多|苹果| 1个

到目前为止,这是我建立的查询:

SELECT Client_name, brand 
  FROM (SELECT Client_name, brand, ROW_NUMBER() OVER (PARTITION BY Client_name ORDER BY freq DESC) AS rn
          FROM (  SELECT Client_name, brand, COUNT('x') AS freq
                  FROM (SELECT Client_name, substring(Product,5) as brand
                        FROM Orders
                GROUP BY Client_name, brand) frequency) ranked) client
 WHERE rn = 1;

我仍然在努力通过使用子字符串删除品牌名称前的数字(例如#768)。我向我显示了一条错误消息

  

-ERROR:column" frequency.Client_name"必须出现在GROUP BY子句中或用于聚合函数

所以我还没有开始考虑如何添加Order_number列

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我认为你只是将你的group by子句置于错误的位置。尝试将其移至'频率'之后但在')'

之前
SELECT Client_name, brand 
  FROM (SELECT Client_name, brand, ROW_NUMBER() OVER (PARTITION BY Client_name ORDER BY freq DESC) AS rn
          FROM (  SELECT Client_name, brand, COUNT('x') AS freq
                  FROM (SELECT Client_name, substring(Product,5) as brand
                        FROM Orders) frequency GROUP BY Client_name, brand) ranked) client
 WHERE rn = 1;