通过查询获取组中每条记录的MAX值

时间:2018-02-04 14:45:21

标签: sql sql-server

我在SQL中有一个查询:

 select fldCustomer, fldTerminal, COUNT(fldbill)
 from tblDataBills
 group by fldCustomer, fldTerminal
 order by fldCustomer 

结果如下:

 fldCustomer    fldTerminal (number of bills)
 0  1   19086
 0  2   10
 0  5   236
 1  1   472
 1  5   3
 1  500 19
 2  1   292
 2  500 22

如何获得每位客户的MAX计数,以便得到像

这样的结果
 0 1 19086
 1 1 472
 2 1 292

提前致谢!

2 个答案:

答案 0 :(得分:2)

将子查询与row_number()

一起使用
select fldCustomer, fldTerminal, cnt
from (select fldCustomer, fldTerminal, COUNT(*) as cnt,
             row_number() over (partition by fldCustomer order by count(*) desc) as seqnum
      from tblDataBills
      group by fldCustomer, fldTerminal
     ) db
where seqnum = 1
order by fldCustomer ;

请注意,如果出现关联,则会随意返回其中一行。如果您想要所有这些内容,请使用rank()dense_rank()

答案 1 :(得分:1)

这可能需要RANK()函数

的一些小技巧

SELECT fldCustomer, fldTerminal, [(number of bills)]
FROM (
    SELECT fldCustomer, fldTerminal, COUNT(fldbill) [(number of bills)],
        RANK() OVER (PARTITION BY fldCustomer ORDER BY COUNT(fldbill) DESC) Ranking
    FROM tblDataBills
    GROUP BY fldCustomer, fldTerminal
) a
WHERE Ranking = 1