选择查询,其中具有相同ID的行仅返回具有最新日期字段的行

时间:2013-04-30 20:21:12

标签: sql

我在弄清楚如何进行以下查询时遇到了一些麻烦。我想为表1中的每个唯一ID返回一行,即使date为null但如果有多个具有相同ID的行,我只想返回具有最新日期的id。任何帮助将不胜感激

Select  a.ID, a.[zip code], b.date
            from table1 a   

            left join table 2 b on a.ID = b.ID  
            Where a.[Zip Code] = '78701' 
Group by a.ID, a.[zip code], b.date
            Order by a.[zip code] asc

2 个答案:

答案 0 :(得分:3)

您可以使用子查询为每个ID选择table2中的最大日期:

SELECT a.ID, a.[zip code], b.date
FROM table1 a   
LEFT JOIN (SELECT ID, MAX(date) AS date
           FROM table2
           GROUP BY ID) b ON a.ID = b.ID  
WHERE a.[Zip Code] = '78701' 
ORDER BY a.[zip code] ASC

答案 1 :(得分:2)

您也可以通过更改查询获得相同的结果:

SELECT    a.ID, a.[zip code], MAX(b.date) AS [date]
FROM      table1 AS a    
              LEFT JOIN table2 AS b 
                  ON a.ID = b.ID  
WHERE     a.[Zip Code] = '78701' 
GROUP BY  a.ID, a.[zip code]
ORDER BY  a.[zip code] ASC ;