选择具有唯一属性的行

时间:2013-04-01 13:40:31

标签: sql sql-server-2008

我有下表

ind_id      name                 value       date
----------- -------------------- ----------- ----------
1           a                    10          2010-01-01
1           a                    20          2010-01-02
1           a                    30          2010-01-03
2           b                    40          2010-01-01
2           b                    50          2010-01-02
2           b                    60          2010-01-03
2           b                    70          2010-01-04
3           c                    80          2010-01-01
3           c                    90          2010-01-02
3           c                    100         2010-01-03
3           c                    110         2010-01-04
3           c                    120         2010-01-05
4           d                    130         2010-01-05

如何选择具有唯一ind_id属性的行?无论每个ind_id的行数肯定是多少。我在结果集中需要4行。我正在使用SQL Server 2008.谢谢

1 个答案:

答案 0 :(得分:4)

为此,您要使用Windows函数:

select ind_id, name, value, date
from (select t.*, row_number() over (partition by ind_id order by (select NULL)) as seqnum
      from t
     ) t
where seqnum = 1;

如果您只想要出现一次,请使用:

select ind_id, name, value, date
from (select t.*, count(*) over (partition by ind_id) as NumInds
      from t
     ) t
where numInds = 1