SQL Server:避免子查询

时间:2018-08-06 08:53:11

标签: sql sql-server subquery

我要避免在以下查询中进行子查询:

SELECT ID,[Start_Date],[End_Date],Assignment_Id 
FROM (
    SELECT ID, MIN([Start_Date]) AS [Start_Date], MAX([End_Date]) AS [End_Date]
    FROM EmployeeTable
    WHERE ID IN (123456) AND ([status] ='A' OR ([status] ='C'))
    GROUP BY ID, Assignment_Id 
    ) T
WHERE [End_date] >= CONVERT(VARCHAR(10),GETDATE(),120)

请在上面提供建议。

谢谢。

3 个答案:

答案 0 :(得分:1)

尝试一下:

SELECT ID, MIN([Start_Date]) AS [Start_Date], MAX([End_Date]) AS [End_Date]
FROM EmployeeTable
WHERE ID IN (123456) AND ([status] ='A' OR ([status] ='C'))
GROUP BY ID, Assignment_Id 
HAVING MAX([End_Date]) >= CONVERT(VARCHAR(10),GETDATE(),120)

答案 1 :(得分:1)

您可以在进行聚合后立即将外部where子句与having子句进行转换,而无需使用OR,则可以使用IN直接表示它条款:

 SELECT ID, MIN([Start_Date]) AS [Start_Date], MAX([End_Date]) AS [End_Date]
 FROM EmployeeTable
 WHERE ID = 123456 AND [status] IN ('A','C')
 GROUP BY ID, Assignment_Id
 HAVING MAX([End_Date]) >= CAST(GETDATE() AS DATE);

答案 2 :(得分:0)

SQL中的HAVING子句指定SQL SELECT语句仅应返回聚集值满足指定条件的行。它被添加到SQL语言中,因为WHERE关键字不能与聚合函数一起使用。   通过使用having子句,您可以按分组方式过滤数据     因此您可以轻松使用having,@ joe在他的查询中已经显示了如何使用它

    SELECT ID,Assignment_Id, MIN([Start_Date]) AS [Start_Date], MAX([End_Date]) AS [End_Date]
    FROM EmployeeTable
    WHERE ID IN (123456) AND ([status] ='A' OR ([status] ='C'))
    GROUP BY ID, Assignment_Id 
    HAVING MAX([End_Date]) >= CONVERT(VARCHAR(10),GETDATE(),120)