简体   繁体   English

在SQL中获取表中每一行的最大日期

[英]Get max date for each line in a table in SQL

I edited my answer so the solution for my question is: 我编辑了答案,所以我的问题的解决方案是:

select  DISTINCT e.Cod_proiect
     , p.Descriere
     , p.Stare
     , p.ClientService
     , e.Data
  from ExpPoz as e 
  join Proiecte as p 
    on e.Cod_proiect=p.Cod_proiect 
             join ( 
                     select cod_proiect, max(data) maxDt 
                     from ExpPoz
                     group by cod_proiect 
                  ) latest on latest.cod_proiect = e.cod_proiect and latest.maxDt = e.Data and p.Stare='I'

Which gives the following error: Subquery returned more than 1 value I am trying to get every line with the maximum date. 这将产生以下错误:子查询返回了多个值,我试图获取具有最大日期的每一行。

I have the following table structure: 我具有以下表结构:

a    date1
a    date2
a    date3
b    date4
b    date5

The output should be, supposing that date3 and date5 are the oldest/biggest: 输出应该是,假设date3和date5是最旧/最大的:

a   date3
b   date5

Thanks in advance. 提前致谢。

This should do the trick: 这应该可以解决问题:

select  e.Cod_proiect
      , p.Descriere
      , p.Stare
      , p.ClientService
from ExpPoz as e join Proiecte as p on e.Cod_proiect=p.Cod_proiect 
                 join ( 
                         select cod_proiect, max(data) maxDt 
                         from ExpPoz
                         group by cod_proiect 
                      ) latest on latest.cod_proiect = e.cod_proiect and latest.maxDt = e.Data
where p.Stare='I'

Please note that the way you have written the joins is very old and it is better and more clear if you use the modern join style. 请注意,您写的方式joins是很老,它是更好,更清楚,如果你使用现代化的join风格。 In this query I selected everything you need and joined once with the latest record per cod_proiect . 在此查询中,我选择了您需要的所有内容,并根据cod_proiect的最新记录加入了一次。

You might try this: 您可以尝试以下方法:

SELECT cod_proiect,
       MAX(data)
FROM
(
  SELECT DISTINCT
         ep.cod_proiect,
         ep.data
  FROM   ExpPoz   ep
  JOIN   Proiecte pr
    ON   ep.cod_proiect = pr.cod_proiect
   AND   pr.stare = 'I'
)
GROUP BY cod_proiect;

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

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