2

我在弄清楚如何执行以下查询时遇到了一些麻烦。我想为表 1 中的每个唯一 ID 返回一行,即使日期为空,但如果有多个具有相同 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
4

2 回答 2

3

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

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
于 2013-04-30T20:24:49.023 回答
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 ;
于 2013-04-30T20:41:53.420 回答