[英]Select minimal values from two different columns
I have to do a SQL statement to select for each day the min value from a column and when the value Order is the same the Max value from percentage. 我必须执行一条SQL语句以每天从列中选择最小值,当值Order相同时,从百分比中选择最大值。
Example: 例:
Date Order Percentage
-------------------------------------------
01-03-2016 1 0
01-03-2016 2 20
02-03-2016 1 0
02-03-2016 2 20
03-03-2016 2 50
03-03-2016 2 20
The result that I want is something like: 我想要的结果是这样的:
Date Order Percentage
-------------------------------------------
01-03-2016 1 0
02-03-2016 1 0
03-03-2016 2 50
You could use row_number
to sort the rows within each such group, and take the first one per group: 您可以使用
row_number
对每个此类组中的行进行排序,并采用每个组中的第一个:
SELECT [Date], [Order], [Percentage]
FROM (SELECT [Date], [Order], [Percentage],
ROW_NUMBER() OVER (PARTITION BY [Date]
ORDER BY [Order] ASC, [Percentage] DESC) AS rk
FROM mytable) t
WHERE rk = 1
If you're using SQL Server 2012+, you could use the following solution: 如果您使用的是SQL Server 2012+,则可以使用以下解决方案:
SELECT DISTINCT
[Date],
FIRST_VALUE ([Order]) OVER (PARTITION BY [Date] ORDER BY [Order] ASC, [Percent] DESC),
FIRST_VALUE ([Percent]) OVER (PARTITION BY [Date] ORDER BY [Order] ASC, [Percent] DESC)
FROM (
VALUES('2016-03-01', 1, 0),
('2016-03-01', 2, 20),
('2016-03-02', 1, 0),
('2016-03-02', 2, 20),
('2016-03-03', 2, 50),
('2016-03-03', 2, 20)
) AS t([Date], [Order], [Percent])
How does it work? 它是如何工作的? For each partition (ie "group") we're selecting the first value, ordered by
[Order]
. 对于每个分区(即“组”),我们选择第一个值,按
[Order]
排序。 If two first values for [Order]
are the same, then order by [Percent]
descendingly. 如果
[Order]
两个第一个值相同, [Percent]
降序排列。 Ie pretty much the requirement from your question. 即几乎是您问题的要求。
Because the first value is the same for the entire partition, we can use DISTINCT
to remove duplicates, afterwards. 因为第一个值对于整个分区都是相同的,所以我们可以在以后使用
DISTINCT
删除重复项。
Be cautious with this solution, especially on SQL Server . 请谨慎使用此解决方案, 尤其是在SQL Server上 。 A
ROW_NUMBER()
based solution as suggested here will outperform mine, slightly on Oracle, and drastically on SQL Server (see comments) 此处建议的基于
ROW_NUMBER()
的解决方案将胜过我的解决方案,在Oracle上略胜一筹,在SQL Server上则大幅度提高 (请参阅注释)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.