使用count(*)进行计算时,如何找到每组中的最大值?

时间:2016-05-18 13:10:24

标签: sql db2

我一直在尝试使用来自其他帖子的建议来查找组中每个成员的最大值,但似乎这是一个不同的问题,因为计数器基于计数(*)而不是特定列。

我的桌子上有几列;我需要的:日期和分支。表的每条记录代表该分支中的一个事务。我需要知道每个日期哪个是更多交易的分支以及完成了多少交易。

我开始时:

Select date, branch, count(*) as total
from table
group by date, branch

我尝试了最大值(总计),但这只会给我一行而不是每组一个。

我尝试加入自己,就像这样,但它不起作用,因为格言没有在有条款中被识别:

Select date, branch, count(*) as maxim
(Select date, branch, count(*) as total
from table
group by date, branch) a
having maxim=max(total)
group by date, branch

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个:

select t1.date, t2.branch, t1.max_total
from (
  select date, max(total) as max_total
  from (
    select date, branch, count(*) as total 
    from mytable 
    group by date, branch) as x
  group by date    
) as t1    
join (
  select date, branch, count(*) as total 
  from mytable 
  group by date, branch
) as t2 on t1.date = t2.date and t1.max_total = t2.total

我们的想法是将您开始使用的查询作为派生表使用两次:

  • 第一次使用它以获得每date
  • 的最大数量
  • 第二次使用它以提取branch计数等于最大数量的total值。如果是关系,可能会有多个分支。

Demo here

如果DB2支持窗口函数,您可以使用以下内容,如果适用,它们会更有效:

select date, branch, total
from (
  select date, branch, count(*) as total,
         rank() over (partition by date order by count(*) desc) as rn
  from mytable
  group by date, branch) as t
where t.rn = 1

答案 1 :(得分:0)

请尝试以下代码。

DECLARE @table TABLE 
    ([Date] date,Branch varchar(10),trans int)

INSERT INTO @table
    (
        [Date],
        Branch,
        trans
    )
    VALUES
    ('2015-01-01','b1',1),('2015-01-01','b1',2),('2015-01-01','b1',3),
    ('2015-01-02','b1',4),('2015-01-02','b1',5),('2015-01-02','b1',6),
    ('2015-01-01','b2',1),('2015-01-01','b2',2),('2015-01-01','b2',3)

Select 
    [Date], Branch, COUNT(trans) AS total
FROM 
    @table
GROUP By 
    [Date], Branch
    ORDER BY [Date]