我正在努力想出一个查询来实现SQL中下表所需的返回数据:
我想获得给定日期和期间范围内的最大订单的Value1和Value2。我有以下查询来获取给定范围内每个日期周期对的最大订单编号 - 但是,我似乎无法获得该订单的Value1和Value2。
SELECT
Date, Period, MAX(Order)
FROM
tableName
WHERE
((Date = '2017-02-27' AND Period>= 10) OR (Date = '2017-02-28' AND Period<= 10))
GROUP BY
Date, Period
答案 0 :(得分:4)
使用row_number()
:
SELECT Date, Period, Order
FROM (SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY Date, Period ORDER BY Order DESC) as seqnum
FROM tableName
WHERE (Date = '2017-02-27' AND Period >= 10) OR
(Date = '2017-02-28' AND Period <= 10)
) t
WHERE seqnum = 1;
答案 1 :(得分:1)
您可以使用窗口函数row_number
:
select *
from (
select t.*, row_number() over (
partition by date, period order by [Order] desc
) rn
from your_table t
where (
date = '2017-02-27'
and Period >= 10
)
or (
date = '2017-02-28'
and Period <= 10
)
) t
where rn = 1;
答案 2 :(得分:0)
如果您想要的只是结果集的顶行,为什么不使用TOP运算符?
SELECT TOP 1 [Date], [Period], [Order], Value1, Value2
FROM tableName
WHERE ((Date = '2017-02-27' AND Period>= 10) OR (Date = '2017-02-28' AND Period<= 10))
ORDER BY [Order] DESC