Sql:Aggregation First()在Order by和Group by之后

时间:2013-04-11 08:34:08

标签: sql

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因为从subselect我得到的A值分别是3,4,1。

2 个答案:

答案 0 :(得分:0)

查询:

<强> SQLFIDDLEExample

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 |

答案 1 :(得分: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

只选择更快的那个