【问题标题】:How do I Improve T-SQL query performance for retrieving the most recent date?如何提高检索最近日期的 T-SQL 查询性能?
【发布时间】:2023-01-13 21:13:13
【问题描述】:

我有一个包含列的 employee

employee_id, name, hire_date, termination_date, rehire_date, is_active

在 SQL Server 中。我想检索每个员工最近的雇用、终止或重新雇用日期,但前提是该员工处于活动状态。

结果应包括 employee_idname 和最近的日期。如何通过单个查询实现此目的?

我可以使用以下方法来做到这一点:

SELECT 
    employee_id, name, MAX(date) as most_recent_date
FROM 
    (SELECT 
         employee_id, name, hire_date AS date 
     FROM 
         employee
     UNION
     SELECT 
         employee_id, name, termination_date 
     FROM 
         employee
     UNION
     SELECT 
         employee_id, name, rehire_date 
     FROM 
         employee) AS t
WHERE 
    employee_id IN (SELECT employee_id 
                    FROM employee 
                    WHERE is_active = 1)
GROUP BY 
    employee_id, name

这个解决方案似乎可行,但我不确定它是否是最有效的方法。我也担心员工表很大时的性能。

谁能建议一种更好、更有效的方法来做到这一点?

【问题讨论】:

  • 为什么在WHERE 子句中需要这个子查询?只需使用WHERE is_active = 1 ..... 完成!
  • UNIONs 更改为 unpivot 可能会有所改进,因为它不会导致对表进行 3 次扫描,也不会导致昂贵的 DISTINCT。也不要将 WHERE 放在子查询中,将它放在要逆透视的数据集的 WHERE 中。

标签: sql sql-server tsql


【解决方案1】:

你可以试试这个。

SELECT employee_id, name, (SELECT Max(v) FROM (VALUES (hire_date), (termination_date),(rehire_date)) AS value(v))  as most_recent_date
                    FROM employee 
                    WHERE is_active = 1 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-17
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多