如何选择按日期排序的具有不同列值的行?

时间:2013-02-01 16:43:42

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我有这张桌子:

create table #tmp
(
  column1 varchar(3),
  column2 varchar(5),
  column3 datetime,
  column4 int
)

insert into #tmp values ('AAA', 'SKA', '2013-02-01 00:00:00', 10)
insert into #tmp values ('AAA', 'SKA', '2013-01-31 00:00:00', 15)
insert into #tmp values ('AAA', 'SKB', '2013-01-31 00:00:00', 20)
insert into #tmp values ('AAA', 'SKB', '2013-01-15 00:00:00', 5)
insert into #tmp values ('AAA', 'SKC', '2013-02-01 00:00:00', 25)

我想选择具有不同column2的行,按column3排序。 这是理想的结果:

Col1  Col2   Col3                       Col4
AAA   SKB    2013-01-15 00:00:00.000    5
AAA   SKA    2013-01-31 00:00:00.000    15
AAA   SKC    2013-02-01 00:00:00.000    25

我该怎么办?
我正在使用MS SQL 2005和2008

5 个答案:

答案 0 :(得分:3)

试试这个

;with cte as 
(
  select *, 
  row_number() over (partition by column1, column2 
             order by column3) rnk
  from #tmp

) select * from cte where rnk = 1
  order by column3;

SQL DEMO HERE

答案 1 :(得分:0)

这应该做

http://sqlfiddle.com/#!3/d3dad/11

select * from
(
select max(column1) as column1, column2 as column2, max(column3) as column3, 
  max(column4) as column4
from #tmp
group by column2
) a
order by column3

答案 2 :(得分:0)

这取决于你想要什么。你必须处理其他列。

从确切的数据中,得到确切的结果:

select column1, column2, min(column3), min(column4)
from #tmp
group by column1, column2

但是,通常column3值可能来自与column4值不同的记录,并且如在SQL中编写的那样,如果您有多个具有相同column2值的column1值,则将获得多个结果同一列2.。

答案 3 :(得分:0)

SELECT t.column1, t.column2, t.column3, t.column4
FROM @tmp t
INNER JOIN (SELECT DISTINCT column2, MIN(column3) [column3] FROM @tmp GROUP BY column2) v
    ON t.column2 = v.column2 AND t.column3 = v.column3
ORDER BY t.column3

这将使用最旧的column3获得唯一的column2,并按照按column3排序的结果过滤表

答案 4 :(得分:0)

我认为row_number()更好(Sql-Demo

select column1, column2, column3, column4 
from (
  select column1, column2, column3, column4, 
         row_number() over (partition by column2 order by column3) rn
  from #tmp ) A
where rn=1
order by column3