Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使用两列的最大值选择记录_Sql_Sql Server_Max - Fatal编程技术网

Sql 使用两列的最大值选择记录

Sql 使用两列的最大值选择记录,sql,sql-server,max,Sql,Sql Server,Max,我有一张桌子的布局与此相似。我需要选择具有最高年值和最高月值的不同供应商编号 卖方每月: id Vendor Year month More stuff(More columns) ---|---------|-------|-------|---------| 1 | 93000 | 2017 | 3 | sadf | 2 | 93000 | 2017 | 2 | asdf | 5 | 93000 | 2017 | 1

我有一张桌子的布局与此相似。我需要选择具有最高年值和最高月值的不同供应商编号

卖方每月:

id  Vendor    Year     month    More stuff(More columns)
---|---------|-------|-------|---------|
1  | 93000   | 2017  | 3     | sadf    |
2  | 93000   | 2017  | 2     | asdf    |
5  | 93000   | 2017  | 1     | asdf    |
3  | 93000   | 2016  | 12    | fff     |
4  | 93000   | 2016  | 11    | ffff    |
6  | 40000   | 2017  | 2     | fff     |
7  | 40000   | 2017  | 1     | fff     |
8  | 40000   | 2016  | 12    | fff     |
结果是这样的。我一生都不能提出一个能满足我需要的问题

id  Vendor    Year     month    More stuff(More columns)
---|---------|-------|-------|---------|
1  | 93000   | 2017  | 3     | sadf    |
6  | 40000   | 2017  | 2     | fff     |

任何帮助都将不胜感激

快速回答,使用
NOT EXISTS
验证同一id中没有其他行的年份较晚或年份较晚,但月份较晚:

select v1.*
from VENDORMONTHLY v1
where not exists (select 1 from VENDORMONTHLY v2
                  where v2.Vendor = v1.Vendor
                    and (v2.Year > v1.year
                      or (v2.Year = v1.Year and v2.Month > v1.Month)))
如果是最新的行连接,将返回两行


核心ANSI SQL-99。将在任何dbms上运行

快速回答,使用
NOT EXISTS
验证同一id中没有其他行的年份较晚或年份较晚,但月份较晚:

select v1.*
from VENDORMONTHLY v1
where not exists (select 1 from VENDORMONTHLY v2
                  where v2.Vendor = v1.Vendor
                    and (v2.Year > v1.year
                      or (v2.Year = v1.Year and v2.Month > v1.Month)))
如果是最新的行连接,将返回两行


核心ANSI SQL-99。将在任何dbms上运行

如果您使用的数据库(SQL Server、Oracle、Postgres等)支持窗口功能,您可以
排名
(或者
行号
,如果每个供应商每年只需要一行-月组合)

在SQL server中,使用带领带的
top可以更好地实现这一点:

Select top 1 with ties *
From vendormonthly
Order by rank() over (
     partition by vendor
     order by year desc, month desc
)

如果您使用的是支持窗口功能的数据库(SQL Server、Oracle、Postgres等),您可以
排名
(或者
行数
,如果每个供应商每年只需要一行/月组合)

在SQL server中,使用带领带的
top可以更好地实现这一点:

Select top 1 with ties *
From vendormonthly
Order by rank() over (
     partition by vendor
     order by year desc, month desc
)

您正在使用哪个数据库?使用sql Server在这种情况下,基于窗口函数的解决方案将是更好的选择,因为只有一个表读取发生。您正在使用哪个数据库?使用sql Server在这种情况下,基于窗口函数的解决方案将是更好的选择,因为只有一个表读取发生。