计算SQL Server中的行结果

时间:2016-05-06 17:00:49

标签: sql sql-server select count

我需要你的帮助,我有这个SQL:

SELECT 
    (SELECT 
         COUNT(b.IDPerfilPortal) 
     FROM 
         UseCRM.dbo.Produtos b 
     WHERE 
         a.IDProduto = b.ID AND b.IDPerfilPortal = 1) AS Completo, 
    (SELECT 
         COUNT(b.IDPerfilPortal) 
     FROM 
         UseCRM.dbo.Produtos b 
     WHERE 
         a.IDProduto = b.ID AND b.IDPerfilPortal >= 2) AS Segmentado
FROM 
    UseCRM.dbo.Contratos a
WHERE 
    (a.DataHoraCancelamento IS NULL) 
    AND (GETDATE() BETWEEN a.DataInicio AND a.DataTermino)

我得到了这个:

Completo  Segmentado
--------------------
    1         0
    0         1
    1         0
    1         0
    1         0

我需要计算Completo和Segmentado中的产品数量。像这样:

Completo  Segmentado
--------------------
  100         55

我只需要一排。我该怎么办?

1 个答案:

答案 0 :(得分:3)

不是对不同的项目进行两次计数,而是可以对这样的情况进行总结:

SELECT 
    sum(case when b.IDPerfilPortal = 1 then 1 else 0 end) AS Completo, 
    sum(case when b.IDPerfilPortal >= 2 then 1 else 0 end) AS Segmentado
FROM
    UseCRM.dbo.Contratos a
    join UseCRM.dbo.Produtos b on a.IDProduto = b.ID
WHERE 
    (a.DataHoraCancelamento IS NULL) 
    AND (GETDATE() BETWEEN a.DataInicio AND a.DataTermino)