所以,我在这一个人的头上碰到了我的头...... 我有一个表(几百万行)看起来像这样:
ID Time Area Name
1 2017-01-01 01:42 21 Test
1 2017-01-02 02:13 21 Test
1 2017-02-01 12:45 30 N/A
1 2017-03-12 02:23 41 N/A
2 2017-02-15 04:25 20 N/A
我想运行一个查询,选择某个ID的最新区域; 结果是这样的:
ID Time Area Name
1 2017-01-02 02:13 21 Test
1 2017-02-01 12:45 30 N/A
1 2017-03-12 02:23 41 N/A
select max(Time),
"of every area"
from TABLE
where ID = 1
如果有人能给我一个线索,那就太棒了!
答案 0 :(得分:3)
您可以使用ROW_NUMBER
:
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY Area ORDER BY Time DESC) AS rn
FROM table) sub
WHERE rn = 1
答案 1 :(得分:3)
又一个选项(没有子查询和/或额外字段)
示例强>
Select Top 1 with Ties *
From YourTable
Where ID =1
Order By Row_Number() over (Partition By Area Order By [Time] Desc)
<强>返回强>
ID Time Area Name
1 2017-01-02 02:13:00.000 21 Test
1 2017-02-01 12:45:00.000 30 N/A
1 2017-03-12 02:23:00.000 41 N/A
答案 2 :(得分:1)
lad2025是正确的。
要更具体地说明您对特定ID的要求,请使用
myChatHub
使用CTE,您可以使用与
相同的内容SELECT * FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY Area ORDER BY Time DESC) AS rn
FROM table WHERE ID=1) sub
WHERE rn = 1
答案 3 :(得分:1)
或者更老的学校方法是在派生表中使用GROUP BY
SELECT Test.* FROM dbo.testTable Test
INNER JOIN (
SELECT Id, MAX(Time) Time, Area
FROM dbo.testTable
GROUP BY Id, Area
) TestMax ON TestMax.Id = Test.Id AND TestMax.Time = Test.Time AND
TestMax.Area = Test.Area
ORDER BY Test.Id, Test.Area;