简体   繁体   English

如何选择不同的数据?

[英]how do I select distinct data?

I'm new in SQL and I this for my uni project. 我是SQL新手,这是我的uni项目。 I have a table with columns Rego, FirstRego, LastRego, RegoDue . 我有一个带有列Rego, FirstRego, LastRego, RegoDue

Suppose I have the following data: 假设我有以下数据:

  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

In the query output I want the Rego to be once with the highest RegoDue ie the output should look like: 在查询输出中,我希望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

How can I do this? 我怎样才能做到这一点?

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

Firstly you want to find the latest rego due date. 首先,您要查找最新的到期日。 Once you have this you can join on it to filter out the undesired results. 一旦有了这个,您就可以加入其中以过滤掉不需要的结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM