1

我有以下用于存储过程的查询。我试图简化 CASE 语句中的逻辑。具体来说,我想将产品嵌套在用户组中。

SELECT DCMNumber, 
       SUM(CONVERT(INT, CurrentlyAssigned)) AS PriorAssigned
FROM dbo.cauAssignedClaim WITH(NOLOCK)
WHERE RecordType = 'A' 
  AND ([Status] <> 'DE' OR [Status] IS NULL)
  AND DATEADD(dd, 0, DATEDIFF(dd, 0, EntryDate)) 
      BETWEEN 
          CASE 
             WHEN Product IN('LTD', 'LTDCP') AND @UserGroup = '' OR @UserGroup = 'NONE'     
                 THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-30)) 
             WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND @UserGroup = '' OR @UserGroup = 'NONE' 
                 THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-14)) 
             WHEN Product IN('LTD', 'LTDCP') AND @UserGroup IN('SSAT', 'TCMS') 
                 THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-7)) 
             WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND @UserGroup IN('Appeals', 'DMS', 'Life', 'WOP', 'IWOP') 
                 THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-7)) 
          END 
      AND DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1)) 
GROUP BY [Status], DCMNumber
4

1 回答 1

1

这是你原来的:

BETWEEN 
      CASE 
         WHEN Product IN('LTD', 'LTDCP') AND @UserGroup = '' OR @UserGroup = 'NONE'     
             THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-30)) 
         WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND @UserGroup = '' OR @UserGroup = 'NONE' 
             THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-14)) 
         WHEN Product IN('LTD', 'LTDCP') AND @UserGroup IN('SSAT', 'TCMS') 
             THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-7)) 
         WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND @UserGroup IN('Appeals', 'DMS', 'Life', 'WOP', 'IWOP') 
             THEN DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-7)) 
      END 
  AND DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1)) 

可以像这样分解日期函数:

BETWEEN DATEADD(dd, DATEDIFF(dd, 0, GETDATE() - 
      CASE 
         WHEN Product IN('LTD', 'LTDCP') AND @UserGroup IN ('', 'NONE') THEN 30
         WHEN Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND @UserGroup IN ('', 'NONE') THEN 14
         WHEN (Product IN('LTD', 'LTDCP') AND @UserGroup IN ('SSAT', 'TCMS')) 
           OR (Product IN('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND @UserGroup IN('Appeals', 'DMS', 'Life', 'WOP', 'IWOP'))
           THEN 7
      END ))
  AND DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1)) 

根据Product列的可能值,您还可以执行以下操作:

  CASE WHEN Product LIKE 'LTD%' ...
       WHEN Product LIKE 'STD%' ...

最后,您缺少默认情况。您可以通过用一个ELSE子句替换其中一个条件来完全删除它,我强烈建议您这样做。我怀疑最准确的默认值是 30,但可以通过默认值 7 得到最大的简化:

BETWEEN DATEADD(dd, DATEDIFF(dd, 0, GETDATE() - 
      CASE 
         WHEN Product LIKE 'LTD%' AND @UserGroup IN ('', 'NONE') THEN 30
         WHEN Product IN ('STD', 'STDCP', 'SALCN', 'STAT', 'OFFOV') AND @UserGroup IN ('','NONE') THEN 14
         ELSE 7
      END ))
  AND DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1))
于 2013-09-12T18:15:59.347 回答