SQL如何选择两个不同的两个一个而不是

时间:2016-12-09 20:40:33

标签: mysql sql sql-server

我有一张表如:

C1 |C2 |C3 |C4

int|int|int|datetime (day and HH:MM:SS)

我需要写一个查询,每个C1和C2返回最新的C3(就C4而言),它应该是C1(asc),C2(asc)的顺序。

ex:
C1|C2|C3|C4

4 |4 |4 |02.02.2016 10:20:00

4 |4 |6 |02.02.2016 10:21:00

3 |1 |5 |02.02.2016 10:18:00

2 |8 |73 |02.02.2016 11:23:00

5 |3 |-2 |02.02.2016 09:23:00

returns:
C1|C2|C3  =>C1 and C2 asc order!

2 |8 |73

3 |1 |5

4 |4 |6 

5 |3 |-2 

2 个答案:

答案 0 :(得分:0)

对于SQL Server,您可以使用CTE。此CTE根据c1 / c2配对分配行号,最近的c4(日期)为1。

with n as(
    select
        c1,
        c2,
        c3,
        ROW_NUMBER over (partition by c1, c2, order by c4 desc) as rn
    from someTable)

select c1, c2, c3 from n where rn = 1 order by c2

答案 1 :(得分:0)

将此以下查询用于您的目的,

SELECT max(c1),max(c2),max(c3) FROM `table1` GROUP by c1,c2 order by c4 desc,c1 asc,c2 asc
相关问题