按客户和类别划分的最大数量

时间:2014-09-26 15:45:00

标签: sql count max

我的交易数据看起来像这样

Account  ProductCategory  
   1           a
   1           a
   1           b
   2           c
   2           d
   2           d

我需要找到每个客户最常出现的ProductCategory。结果:

Account  ProductCategory
   1           a
   2           d

我的结果很长,有许多嵌套子查询。有什么好主意吗? 提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

大多数数据库都支持ANSI标准窗口函数,尤其是row_number()。您可以使用聚合来获得所需内容:

select Account, ProductCategory
from (select Account, ProductCategory, count(*) as cnt,
             row_number() over (partition by Account order by count(*) desc) as seqnum
      from table t
      group by Account, ProductCategory
     ) apc
where seqnum = 1;

答案 1 :(得分:1)

这可以使用分析SQL完成,或者只使用count over group。根据迈克尔的要求,语法取决于RDBMS。

您可以尝试以下SQL:

select * from
(select account, ProductCategory, ct , ROW_NUMBER() OVER (partition by account, ProductCategory  ORDER BY ct DESC ) As myRank
from  (select account, ProductCategory, count(0) as ct
       from <table>
       group by account, ProductCategory  ) t ) t2
where t2.myRank = 1

答案 2 :(得分:0)

代码:

WITH A AS (SELECT [Account], ProductCategory, COUNT([ProductCategory]) OVER(PARTITION BY ProductCategory) AS [Count]
           FROM tbl_all)
SELECT A.Account, ProductCategory
FROM A INNER JOIN (SELECT Account, MAX([Count]) AS Count FROM A GROUP BY A.Account) AS B ON A.Account=B.Account AND A.Count=B.Count
GROUP BY A.Account, ProductCategory