选择计数案例计算

时间:2015-03-18 13:35:33

标签: sql-server count calc

我有一个MS查询,它选择两个不同记录的计数,然后执行计算以从另一个中减去一个结果,并将结果显示为difference

见下文:

Ticketnumber   |   Createdon    |    Modifiedon  |
00012121       |    16/03/2015  |    15/03/2015  |
00211335       |    10/03/2015  |    17/03/2015  |

SELECT  ( SELECT    COUNT(incidentbase.ticketnumber) AS val2
          FROM      IncidentBase
          WHERE     createdon >= GETDATE() - 7
        ) - ( SELECT    COUNT(incidentbase.ticketnumber) AS val1
              FROM      incidentbase
              WHERE     modifiedon >= GETDATE() - 7
            ) AS difference

我想要的是将结果显示为单个值,具体取决于结果是正数还是负数,类似于:

WHEN difference => 0 then 1
WHEN difference =< 0 then 0 

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

只需使用CASE

SELECT CASE 
          WHEN (SELECT COUNT (incidentbase.ticketnumber) as val2 
                FROM IncidentBase 
                WHERE createdon >= GETDATE()-7) - 
               (SELECT count (incidentbase.ticketnumber) as val1 
                FROM incidentbase 
                WHERE modifiedon >= GETDATE()-7) <= 0 THEN 1
          ELSE 0 
       END AS flag 

答案 1 :(得分:0)

你可以使用&#39; case&#39;像这样:

declare @i1 int=5
select case when @i1 < 0 then 0 
when @i1=> 1 then 1 
end  results1