如何选择不同的数据?

时间:2013-10-20 12:07:57

标签: sql

我是SQL的新手,我是我的uni项目。我有一个包含Rego, FirstRego, LastRego, RegoDue列的表格。

假设我有以下数据:

  Rego      FirstRego                      LastRego                      RegoDue
YGF 615 2011-04-07 00:00:00.000 2011-04-07 00:00:00.000 2012-04-07 00:00:00.000
YGF 615 2011-04-07 00:00:00.000 2012-04-07 00:00:00.000 2013-04-07 00:00:00.000
ZIR 377 2012-10-05 00:00:00.000 2012-10-05 00:00:00.000 2013-10-05 00:00:00.000
ZIR 377 2012-10-05 00:00:00.000 2013-10-05 00:00:00.000 2014-10-05 00:00:00.000
ZJT 795 2012-10-31 00:00:00.000 2012-10-31 00:00:00.000 2013-10-31 00:00:00.000
ZSU 823 2012-04-30 00:00:00.000 2012-04-30 00:00:00.000 2013-04-30 00:00:00.000

在查询输出中,我希望Rego为最高RegoDue一次,即输出应如下所示:

Rego      FirstRego                      LastRego                      RegoDue
YGF 615 2011-04-07 00:00:00.000 2012-04-07 00:00:00.000 2013-04-07 00:00:00.000
ZIR 377 2012-10-05 00:00:00.000 2013-10-05 00:00:00.000 2014-10-05 00:00:00.000
ZJT 795 2012-10-31 00:00:00.000 2012-10-31 00:00:00.000 2013-10-31 00:00:00.000
ZSU 823 2012-04-30 00:00:00.000 2012-04-30 00:00:00.000 2013-04-30 00:00:00.000

我该怎么做?

2 个答案:

答案 0 :(得分:0)

Select * 
From Tbl T1
Where RegoDue =
(
    Select Max(RegoDue)
    From Tbl T2
    Where T2.Rego = T1.Rego
)

答案 1 :(得分:0)

首先,您要查找最新的rego截止日期。一旦你有了这个,你可以加入它来过滤掉不想要的结果。

select
    t.Rego, t.FirstRego, t.LastRego, lr.LatestRegoDue as RegoDue
from Table1 t
    join
    (
        select
           Rego, max(RegoDue) as LatestRegoDue
        from Table1
        group by Rego
    ) lr on t.Rego = lr.Rego and t.RegoDue = lr.LatestRegoDue