简体   繁体   English

SQL:过滤(行)在组(列)中具有最大值

[英]SQL: Filter (rows) with maximum value within groups (columns)

I need to filter for rows based on maximum values of version within month and location.我需要根据月份和位置内的版本最大值过滤行。 Using SQL.使用 SQL。

For example, I have table below where there are version 1 and 2 of June & NYC, I wanted to filter for only the row of version 2 with revenue 11. Or for January & NYC, I wanted to get only the row with revenue 15.例如,我有下表,其中有 6 月和纽约的版本 1 和 2,我只想过滤收入为 11 的版本 2 的行。或者对于 1 月和纽约,我只想得到收入为 15 的行.

Month   Location Version    Revenue
June    NYC     1            10
June    NYC     2            11
June    LA      3            12
January NYC     1            13
January NYC     2            14
January NYC     3            15
January LA      1            16
January LA      2            17

Result:结果:

Month   Location  Version   Revenue
June    NYC        2          11
June    LA         3          12
January NYC        3          15
January LA         2          17

Edit to change name of column to Revenue to remove confusion.编辑以将列名称更改为收入以消除混淆。 I do not need the max value of revenue, only revenue that goes with max version of that month and that location.我不需要收入的最大值,只需要与该月和该位置的最大版本相匹配的收入。

You can also use joins as an alternative to correlated subqueries, eg:您还可以使用连接作为相关子查询的替代方法,例如:

select t1.* from YourTable t1 inner join
(
    select t2.month, t2.location, max(t2.version) as mv
    from YourTable t2
    group by t2.month, t2.location
) q on t1.month = q.month and t1.location = q.location and t1.version = q.mv

Change YourTable to the name of your table.YourTable更改为您的表的名称。

A typical method is filtering using a correlated subquery:一种典型的方法是使用相关子查询进行过滤:

select t.*
from t
where t.version = (select max(t2.version)
                   from t t2
                   where t2.month = t.month and t2.location = t.location
                  );

Another alternative that minimizes subqueries is to use the row_number() window function.另一种最小化子查询的替代方法是使用row_number()窗口函数。 (You don't mention which database server you're using, but most of them support it.) (您没有提到您使用的是哪个数据库服务器,但大多数都支持它。)

SELECT month, location, version, revenue
FROM (SELECT month, location, version, revenue
           , row_number() OVER (PARTITION BY month, location ORDER BY version DESC) AS rn
      FROM your_table)
WHERE rn = 1;

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

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