繁体   English   中英

从一组行中获取一列的最大值

[英]Get the max value of a column from set of rows

我有这样的桌子

Table A:

Id Count
1  4
1  16
1  8
2  10
2  15
3  18
etc

Table B:
1 sample1.file
2 sample2.file
3 sample3.file

TABLE C:
Count fileNumber
16 1234
4 2345
15 3456
18 4567

等等...

我想要的是这个

1 sample1.file 1234
2 sample2.file 3456
3 sample3.file 4567

从使用的表AI中获取最大值

  Select MAX (Count) from A where Id='1'

这很好用,但是我的问题是将数据与另一个表合并时。

当我加入表B和表A时,我需要获取所有ID的最大值,而在查询中我不知道ID是什么。

这是我的查询

SELECT B.*,C.*
JOIN A on A.Id = B.ID
JOIN C on A.id = B.ID
WHERE (SELECT MAX(COUNT) 
         FROM A 
        WHERE Id = <what goes here????>)

总而言之,我想要的是表B中的值,表c中的FileNumber(其中,表A中ID的最大计数)。

更新:更正上面的表C。 看起来我需要表A。

我认为这是您要查找的查询:

select b.*, c.filenumber from b
join (
  select id, max(count) as count from a
  group by id
) as NewA on b.id = NewA.id
join c on NewA.count = c.count

但是,您应考虑到我不明白为什么对于tableA中的id = 1,您选择16以与表C匹配(这是最大值),对于tableA中的id = 2,您选择10以与表C匹配。 C(最小值)。 我以为您在两种情况下都表示最大。

编辑:

我看到您已经更新了tableA数据。 给定先前的数据,查询将得出此结果:

+----+---------------+------------+
| ID |   FILENAME    | FILENUMBER |
+----+---------------+------------+
|  1 | sample1.file  |       1234 |
|  2 | sample2.file  |       3456 |
|  3 | sample3.file  |       4567 |
+----+---------------+------------+

这是一个有效的例子

使用Mosty的工作示例(将列名的关键字计数重命名为cnt),这是另一种方法:

with abc as (
  select
    a.id,
    a.cnt,
    rank() over (
      partition by a.id
      order by cnt desc
    ) as rk,
    b.filename
  from a join b on a.id = b.id
)
  select
    abc.id, abc.filename, c.filenumber
  from abc join c
  on c.cnt = abc.cnt
  where rk = 1;
select
      PreMax.ID,
      B.FileName,
      C2.FileNumber
   from
      ( select C.id, max( C.count ) maxPerID
           from TableC C
           group by C.ID
           order by C.ID ) PreMax

         JOIN TableC C2
            on PreMax.ID = C2.ID
           AND PreMax.maxPerID = C2.Count

         JOIN TableB B
            on PreMax.ID = B.ID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM