SQL COALESCE返回更多的1个值或备用解决方案

时间:2013-09-25 20:25:08

标签: sql-server

帖子已经修改!!! ....

我需要有关WHERE条件的帮助,如下所示:

ID#1属于工程部。

ID#2属于销售部门

ID#3属于其他部门。

ID#4属于Eng-Level2部门

ID#5属于Eng-Level3部门

ID#6属于Eng-Level4部门

我试图完成的是,如果ID#1日志运行此报告,它将显示属于他的活动(ID#1),AND Eng-Levelx(ID#4,ID#5和ID#6) )。但是,如果ID属于其他部门(ID#2& 3),则仅向他/她显示以下活动。

这是我的非工作查询:

SELECT * FROM dbo.CRM_Activity
WHERE 
(ActivityOwnerID = 1579
AND [Status] = 'Open'
AND Status <> 'Deleted')
OR
    ActivityOwnerID IN (
        SELECT COALESCE(
            (SELECT Tech_ID FROM dbo.employee WHERE tech_ID = 1579 and POSITION = 'Engineering')
            ,  (SELECT Tech_ID FROM dbo.employee WHERE LEFT(first_name, 4) = 'Eng-')  --- THIS ONE FAILED BECAUSE IT RETURNS MULTIPLE RECORDS
        )
    )
    AND [Status] = 'Open'

ORDER BY CreatedDate DESC

2 个答案:

答案 0 :(得分:1)

您可以改为使用UNION,这样就可以从两个查询中获得唯一Tech_ID的列表。

SELECT * FROM dbo.CRM_Activity
WHERE 
    ActivityOwnerID IN (

            SELECT Tech_ID FROM dbo.employee WHERE tech_ID = 1579 and POSITION = 'Engineering'
            UNION
            SELECT Tech_ID FROM dbo.employee WHERE LEFT(first_name, 4) = 'Eng-'
        )

答案 1 :(得分:0)

在您的情况下,SELECT COALESCE(....可以返回多个值,因为IN允许多个值,但SELECT Tech_ID FROM dbo.employee WHERE tech_ID = 1579 and POSITION = 'Engineering'左右的结果必须为1,因为COALESCE需要表达式(不是结果集)。