2015-06-24 49 views
0

我有一個表,看起來像這樣:SQL:選擇每個組獨特的最小值和改變值

標識日期分類

x 1995  A 
x 1996  B 
z 1995  B 
z 1996  A 
y 1995  B 
y 1996  B 

我想要做的是設置類別到每個ID的最短日期的價值。所以,最後的結果會是什麼樣子:

標識日期分類

x 1995  A 
x 1996  A 
z 1995  B 
z 1996  B 
y 1995  B 
y 1996  B 

有誰知道如何在SQL這樣做嗎?謝謝!

回答

1

試試這個

declare @t table (id char(1), date int, category char(1)) 
insert into @t 
select 'x', 1995,  'A' union all 
select 'x', 1996 ,  'B' union all 
select 'z', 1995 , 'B' union all 
select 'z', 1996 , 'A' union all 
select 'y', 1995 , 'B' union all 
select 'y', 1996  , 'B' 

select t1.Id,t1.Date,t2.category from @t as t1 left join 
( 
select t1.Id,t1.Date,t1.category from @t as t1 inner join 
    (
    select ID, min(Date) as Date from @t group by ID 
    ) as t2 on t1.Id=t2.Id and t1.Date=t2.Date 
) as t2 on t1.Id=t2.Id 
+1

組通過將返回3行內連接將最終返回3排。 –

+0

我已編輯帖子 – Madhivanan

1

這應該這樣做雖然有可能是一個更聰明的辦法:

select table1.id, table1.date, t3.category 
from table1 
join (
    select t1.id, t1.category 
    from table1 t1 
    join (
    select id, min(date) as min_date 
    from table1 
    group by id 
) t2 on t1.id = t2.id and t1.date = t2.min_date 
) t3 on table1.id = t3.id 

在源表被命名爲table1查詢。的邏輯是,內源性表限制了外到分鐘(日期)

Sample SQL Fiddle

1

可以使用子查詢:

select 
    id, 
    date, 
    (
    select category 
    from mytable x 
    where x.id = m.id 
    and not exists 
    (
     select * 
     from mytable older 
     where older.id = x.id 
     and older.date < x.date 
    ) 
) as oldest_category 
from mytable m;