SQL Server - 选择查询中的选择条件

时间:2018-01-16 07:20:46

标签: sql-server sql-server-2012

我有两个表Companies1Companies2,其中公司名称始终存在于Companies2表中,但可能位于Companies1表中,也可能不存在。

我需要应用这个条件:

CONVERT(VARCHAR(11), GETDATE(), 112) BETWEEN Start AND End

仅当Companies1表中存在名称时

SELECT DISTINCT 
    COALESCE(NULLIF(Company1_Name, ''), Company2_Name) Company
FROM 
    [Companies1] AS C1 
LEFT JOIN 
    [Companies2] AS C2 ON (C1.Company1_Name = C2.Company2_Name) 
WHERE 
    Company1_Name = ('XYZ') 
    AND CONVERT(VARCHAR(11), GETDATE(), 112) BETWEEN Start AND End

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

请尝试这样的事情。 另外请不要在where子句的列周围使用函数,因为它使查询不可用。

select DISTINCT COALESCE(NULLIF(Company1_Name,''),Company2_Name) Company
FROM [Companies1] as C1 left join [Companies2] AS C2 
on(C1.Company1_Name=C2.Company2_Name) where Company1_Name=('XYZ') 
AND 
CONVERT(VARCHAR(11), getdate(), 112) >= 
        CASE WHEN C1.Company1_Name IS NOT NULL THEN [Start] ELSE CONVERT(VARCHAR(11), getdate(), 112) END

AND 
CONVERT(VARCHAR(11), getdate(), 112) <= 
    CASE WHEN C1.Company1_Name IS NOT NULL THEN [End] ELSE CONVERT(VARCHAR(11), getdate(), 112) END

答案 1 :(得分:0)

SELECT DISTINCT COALESCE(NULLIF(Company1_Name,''),Company2_Name) Company
FROM [Companies1] AS C1 LEFT JOIN [Companies2] AS C2 ON (C1.Company1_Name=C2.Company2_Name) WHERE EXISTS Company1_Name=('XYZ') AND 
CONVERT(VARCHAR(11), getdate(), 112) 
IN BETWEEN Start AND End