我有桌费率
Key Rate Dt
1 2 201401
1 2 201402
1 3 201403
2 1 201308
2 2 201309
2 1 201301
我想选择具有最低Dt的密钥和费率。
所以结果应该是这样的:
Key Rate Dt
1 2 201401
2 1 201308
我试过了:
从Dt =的比率中选择Key,Rate,Dt(从Rates中选择MIN(dt) 按键分组)
但它没有选择特定键的最低日期......你能帮帮我吗? 谢谢
答案 0 :(得分:1)
您可以使用CTE获取相关记录......
;
WITH cteLowestDate
AS ( SELECT [Key]
,Rate
,Dt
,ROW_NUMBER() OVER (PARTITION BY [Key] ORDER BY Dt) AS 'rownum'
FROM Rates
)
SELECT [Key], Rate, Dt
FROM cteLowestDate
WHERE rownum = 1
我添加了SQL Fiddle
答案 1 :(得分:1)
SELECT KEY,
Rate,
Dt
FROM (SELECT KEY,
Min(dt) dt
FROM Rates
GROUP BY KEY) A
JOIN Rates B
ON A.KEY = B.KEY
AND A.dt = B.dt
答案 2 :(得分:0)
我认为你的意思是:
SELECT
yt.key,
yt.rate,
yt.dt
FROM
(
SELECT
key,
MIN(dt) AS min_dt
FROM
rates
GROUP BY
key
) AS kmd
INNER JOIN rates AS yt ON
yt.key=kmd.key AND
yt.dt=kmd.min_dt