SQL - 基于最大日期选择结果的更简洁方法?

时间:2014-12-09 17:11:43

标签: sql sql-server subquery

我有一个连接到多个表的查询。根据一个表的列值,我想要另一个表的键值。但是,当此键值连接到另一个表(目的是识别该键的不同日期值)时,会出现几个日期。我想在返回其他表时返回其最新日期的键值。我有一个有效的查询,但它非常冗余,因为子查询几乎与主查询相同。我不知道是否有技术或更好的方法来实现这一目标。

示例查询:

SELECT distinct TableA.key
    FROM TableA a INNER JOIN TableB b 
        ON a.key = b.Key    
INNER JOIN TableC c ON b.Key2 = c.Key2
INNER JOIN TableD d ON b.Key = d.Key
WHERE b.column1 = XYZ        
AND c.column1 = 123
and d.date = 

(SELECT max(d.date)
    FROM TableA a INNER JOIN TableB b 
        ON a.Key = b.Key   
INNER JOIN TableC c ON b.Key2 = c.Key2
INNER JOIN TableD d ON b.Key = d.Key
WHERE b.column1 = XYZ          
AND c.column1 = 123

)

1 个答案:

答案 0 :(得分:1)

试试这个。按日期desc

使用Top 1 with ties订单
SELECT distinct TOP 1 with ties TableA.key
    FROM TableA a INNER JOIN TableB b 
        ON a.key = b.Key    
INNER JOIN TableC c ON b.Key2 = c.Key2
INNER JOIN TableD d ON b.Key = d.Key
WHERE b.column1 = XYZ        
AND c.column1 = 123
order by  d.date desc