在SELECT语句中使用COUNTS的T-SQL IF ELSE逻辑

时间:2014-05-23 14:50:50

标签: sql sql-server tsql

我要解决的问题是在IF/ELSE语句中使用SELECT逻辑并评估计算的COUNT

如果计算的计数为零,请保持原样。否则 - 减去1.

我需要一些帮助来修改下面的代码,以包含这种逻辑:

COUNT (case when d2.dwContactPK = 0 then d2.dwContactPK end) + COUNT(distinct   d2.dwContactPK)-1 as [AG1],

COUNT(case when d.GeneratedToTMYN = 'Y' and d2.dwContactPK = 0 then d2.dwContactPK end) + 
    COUNT(distinct case when d.GeneratedToTMYN = 'Y' then d2.dwContactPK end) -1 as [AG2],


COUNT(case when d.GeneratedToEloquaSFDCYN = 'Y' and d2.dwContactPK = 0 then d2.dwContactPK end) + 
    COUNT(distinct case when d.GeneratedToEloquaSFDCYN = 'Y' then d2.dwContactPK end) -1 as [AG3], 

3 个答案:

答案 0 :(得分:0)

select case
        when d2.dwContactPK = 0 then d2.dwContactPK
        else COUNT(distinct   d2.dwContactPK)-1
        end as MyAnswer

答案 1 :(得分:0)

您的问题似乎是:

  

我想解决的问题是在a中使用IF / ELSE逻辑   SELECT语句并计算计算的COUNT。

我不清楚您的代码示例与此问题的关系。答案的结构是:

select (case when count( . . . ) = 0 then 0
             else count( . . . ) - 1
        end)

. . .可能包含case语句,但不包括其他聚合函数。

答案 2 :(得分:0)

感谢您的所有输入。最后我把每个语句都附在更大的“case when when”子句中。这可能不是最漂亮的方法,但它可以在这里完成工作:

Case when(COUNT(case when d2.dwContactPK = 0 then d2.dwContactPK end) + 
COUNT(distinct d2.dwContactPK) -1) = -1 then 0 else COUNT(case when d2.dwContactPK = 0 then d2.dwContactPK end) + 
COUNT(distinct d2.dwContactPK) -1 end as [AG1],


Case when(COUNT(case when d.GeneratedToTMYN = 'Y' and d2.dwContactPK = 0 then d2.dwContactPK end) + 
COUNT(distinct case when d.GeneratedToTMYN = 'Y' then d2.dwContactPK end) -1) = -1 then 0 else COUNT(case when d.GeneratedToTMYN = 'Y' and d2.dwContactPK = 0 then d2.dwContactPK end) + 
COUNT(distinct case when d.GeneratedToTMYN = 'Y' then d2.dwContactPK end) -1 end as [AG2],


Case when(COUNT(case when d.GeneratedToEloquaSFDCYN = 'Y' and d2.dwContactPK = 0 then d2.dwContactPK end) + 
COUNT(distinct case when d.GeneratedToEloquaSFDCYN = 'Y' then d2.dwContactPK end) -1) = -1 then 0 else COUNT(case when d.GeneratedToEloquaSFDCYN = 'Y' and d2.dwContactPK = 0 then d2.dwContactPK end) + 
COUNT(distinct case when d.GeneratedToEloquaSFDCYN = 'Y' then d2.dwContactPK end) -1 end as [AG3],