if子句中的if / case语句

时间:2016-02-25 00:57:43

标签: sql

在我的部门参数中,我包含一个值或一个/多个部门ID。

SELECT 
    DEPARTMENT,c.DEPTNAME as DEPARTMENT_DESCRIPTION, c.LOCATION as LOCATION,
    sum(b.qty) as QTY, sum(b.cost) as 'COST', sum(b.nbv) AS 'NBV'
FROM FIX_ASSET A 
right join .SAMPLING b on ASSET_NUMBER=b.ASSET_NUMBER 
left join DEPARTMENT C on A.DEPARTMENT=C.DEPTID 
where BUSINESS_UNIT=1227 and b.year_audit=2016 and taggable='YES'     
group by department, c.DEPTNAME, c.LOCATION

我想要的是在where子句

中添加case / if语句
case when (select count(*) from #tempdept) > 0 
then and fix_asset.department in (select item from #tempdept) 

如果tempdept数据大于0,我会添加条件And department in(select item from #tempdept)

3 个答案:

答案 0 :(得分:1)

你不需要一个案例陈述。只需制作你的WHERE子句

where BUSINESS_UNIT=1227 and b.year_audit=2016 and taggable='YES'
and (
      (
        (select count(*) from #tempdept) > 0 and fix_asset.department in (select item from #tempdept) 
      )
      or
      (select count(*) from #tempdept) = 0
    )

答案 1 :(得分:0)

您可以尝试使用此语法,使用两个嵌套的CASE语句:

case when (select count(*) from #tempdept) > 0 
    then 
        case when fix_asset.department in (select item from #tempdept) 
            then 'dosomething'
            else 'dosomething'
        end
    else
        'dosomething'
end AS 'something'

答案 2 :(得分:0)

试试这个

EntityManager::findOneBy([$paramKey => $paramValue])

表示如果where BUSINESS_UNIT=1227 and b.year_audit=2016 and taggable='YES' AND (CASE WHEN (select count(*) from #tempdept) > 0 THEN fix_asset.department IN (select item from #tempdept) ELSE 1 = 1 END) 大于0,则检查count(*)条件,否则包括记录。