我会在哪里向此SQL查询添加IF语句?

时间:2015-07-28 18:44:12

标签: sql sql-server if-statement

我需要添加一个IF语句,说明:如果item.decifld1 = 0或NULL,则将其视为999999,否则只需使用找到的item.decifld1的值。

CODE

SELECT
   job.whse
  ,SUM(CEILING((job.qty_released/item.decifld1))) AS Sum_pallet_qty_released
  ,SUM(CEILING((job.qty_complete/item.decifld1))) AS Sum_pallet_qty_complete
  ,SUM(CEILING(((job.qty_released-job.qty_complete)/item.decifld1))) AS Sum_pallet_qty_remaining
  ,SUM(job.qty_released) AS Sum_qty_released
  ,SUM(job.qty_complete) AS Sum_qty_complete
  ,SUM(job.qty_released-job.qty_complete) AS Sum_qty_remaining
FROM
  job
INNER JOIN
  item
ON
  job.item=item.item
WHERE
  job.job_date = @job_date
  AND job.job NOT LIKE 'HK%'
  AND job.job NOT LIKE 'HR%'
  AND job.job NOT LIKE 'MMR%'
  AND job.job NOT LIKE 'SS%'
  AND job.job NOT LIKE 'SU%'
  AND job.job NOT LIKE 'TR%'
  AND job.job NOT LIKE 'WC%'
  AND job.job NOT LIKE 'MN%'
  AND job.job NOT LIKE 'QC%'
  AND job.job NOT LIKE 'SC%'
  AND job.job NOT LIKE 'CLN%'
  AND job.job NOT LIKE 'NR%'  
  AND job.job NOT LIKE 'WHS%'
  AND job.job NOT LIKE 'Bill%'
  AND job.job NOT LIKE 'PR%'
  AND job.job NOT LIKE 'WR%'
GROUP BY
  job.whse

2 个答案:

答案 0 :(得分:1)

使用

ISNULL(NULLIF(item.decifld1, 0), 999999)

而不是

item.decifld1

有关详细信息,请参阅NULLIFISNULL的文档。

答案 1 :(得分:1)

IF不是SQL。它是程序性SQL,但在这种情况下,它用于流量控制并确定要执行哪些查询,而不是更改查询中的数据值。

在查询中,您需要一个CASE表达式。

CASE 
    WHEN item.decifld1 = 0 OR item.decifld1 IS NULL THEN 999999 
    ELSE item.decifld1 
END

在您的特定查询中:

SELECT
   job.whse
  ,SUM(CEILING((job.qty_released/CASE WHEN item.decifld1 = 0 OR item.decifld1 IS NULL THEN 999999 ELSE item.decifld1 END))) AS Sum_pallet_qty_released
  ,SUM(CEILING((job.qty_complete/CASE WHEN item.decifld1 = 0 OR item.decifld1 IS NULL THEN 999999 ELSE item.decifld1 END))) AS Sum_pallet_qty_complete
  ,SUM(CEILING(((job.qty_released-job.qty_complete)/CASE WHEN item.decifld1 = 0 OR item.decifld1 IS NULL THEN 999999 ELSE item.decifld1 END))) AS Sum_pallet_qty_remaining
  ,SUM(job.qty_released) AS Sum_qty_released
  ,SUM(job.qty_complete) AS Sum_qty_complete
  ,SUM(job.qty_released-job.qty_complete) AS Sum_qty_remaining
FROM [...]

但是,我猜你正在尝试做的就是当你不能分裂时,除法归零。如果这是真的,那么你真正想要做的就是:

SELECT
     job.whse
    ,SUM(CASE WHEN item.decifld1 = 0 OR item.decifld1 IS NULL THEN 0 ELSE CEILING((job.qty_released/item.decifld1)) END) AS Sum_pallet_qty_released
    ,SUM(CASE WHEN item.decifld1 = 0 OR item.decifld1 IS NULL THEN 0 ELSE CEILING((job.qty_complete/item.decifld1)) END) AS Sum_pallet_qty_complete
    ,SUM(CASE WHEN item.decifld1 = 0 OR item.decifld1 IS NULL THEN 0 ELSE CEILING(((job.qty_released-job.qty_complete)/item.decifld1)) END) AS Sum_pallet_qty_remaining
    [...]

换句话说,如果分母是0NULL,那么只需将整个分词表达式的值视为0。否则,除以值并取上限。现在你不依赖于999999可能足够大以使除法和上限函数返回0这一事实,而是明确地告诉表达式在某些方面表现得特定情况。