1
id | name | value | time |
--------------------------
1  | A | 1 | 1 | 
2  | B | 2 | 2 | 
3  | C | 2 | 3 | 
4  | A | 3 | 3 | 
5  | A | 4 | 2 | 

我预计结果如下:

name | value |
--------------
 A | 3 | 
 B | 2 | 
 C | 2 | 

结果是显示最新时间的名称和值,并且不与名称重复。我尝试查询:

SELECT name,First(value)
FROM
(SELECT name,value,time
FROM test
ORDER BY time DESC
)
GROUP BY name;

但我得到了这个结果:

name | value |
--------------
 A | 1 | 
 B | 2 | 
 C | 2 | 

我不明白为什么 A 值不是 3,因为从子选择中我得到的 A 值分别是 3、4、1。

4

2 回答 2

0

询问:

SQLFIDDLE示例

SELECT t.name,
       (SELECT t1.value
        FROM test t1
        WHERE t1.name = t.name
        ORDER BY t1.time DESC
        LIMIT 1) AS value 
FROM test t
GROUP BY t.name

结果:

| NAME | VALUE |
----------------
|    A |     3 |
|    B |     2 |
|    C |     2 |
于 2013-04-11T08:45:01.267 回答
0

你也可以使用 partitionby

;with cte as (
  select id, row_number() over (order by time desc) rn
  from test
)
select * from test
join cte on test.id = cte.id and rn = 1

只选择一个更快的

于 2013-04-11T08:55:24.083 回答