3

我有这张桌子:

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

4

5 回答 5

4

试试这个

;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 演示在这里

于 2013-02-01T16:58:45.887 回答
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
于 2013-02-01T16:47:13.910 回答
0

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

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

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

但是,一般来说,column3 的值可能来自与 column4 值不同的记录,并且如 SQL 中所写,如果您有多个 column1 值具有相同的 column2 值,您将获得多个具有相同 column2 的结果.

于 2013-02-01T16:48:06.020 回答
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 排序的结果过滤表

于 2013-02-01T17:01:09.657 回答
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
于 2013-02-01T17:18:22.797 回答