SQL COUNT行结果在单独的列中

时间:2017-08-01 08:13:09

标签: sql sql-server

我目前使用它来计算表格中的所有数字或行数,它可以很好地满足我的需要。

SELECT COUNT(*) AS STCount 
  FROM  (SELECT Distinct DPoint, RNum 
           FROM ECount  
          WHERE DType = 'STR' AND Month(EDate) = '07') AS rows

我唯一的问题是我必须重复这个陈述,而每次只改变一些事情。我想联合这些选择,但结果显示在一个单独的列中,下面的示例工作获取结果但将它们全部放在同一列中。任何想法如何让他们在自己的专栏中显示一个STCount和NCCount?

SELECT COUNT(*) AS STCount 
  FROM (SELECT Distinct DPoint, RNum 
          FROM ECount  
         WHERE DType = 'STR' AND Month(EDate) = '07') AS rows 
 UNION 
SELECT COUNT(*) AS NCCount 
  FROM (SELECT Distinct DPoint, RNum 
          FROM ECount  
         WHERE DType = 'NCD' AND Month(EDate) = '07') AS rows

结果将是,

STCount NCCount
  100     202

7 个答案:

答案 0 :(得分:12)

您可以在select子句中进行选择,但不需要from

select (select count(1)
        from  (select distinct DPoint, RNum 
               from ECount
               where DType = 'STR' 
                 and Month(EDate) = '07') as x
       ) as rows1,
      (select count(1)
       from  (select distinct DPoint, RNum 
              from ECount  
              where DType = 'NCD' 
                and Month(EDate) = '07') as x
      ) as rows2;

答案 1 :(得分:6)

您可以使用CASE:

SELECT 
    COUNT (CASE WHEN DType = 'STR' THEN (1)  ELSE NULL END) AS STCount,
    COUNT (CASE WHEN DType = 'NCD' THEN (1)  ELSE NULL END) AS NCCount
    FROM (Select Distinct DType, DPoint, RNum From ECount WHERE Month(EDate) = '07') as rows

答案 2 :(得分:4)

#holder > svg > g > rect

答案 3 :(得分:2)

基本上,您只需要为union语句中的每个列提供占位符:

SELECT COUNT(*) AS STCount, 0 AS NCCount 
FROM (SELECT DISTINCT DPoint, RNum 
      FROM ECount
      WHERE DType = 'STR' AND Month(EDate) = '07') AS rows 
UNION SELECT 0, COUNT(*) 
FROM (SELECT DISTINCT DPoint, RNum 
      FROM ECount
      WHERE DType = 'NCD' AND Month(EDate) = '07') AS rows

以上不符合我添加答案后提供的所需输出。所以,我建议你选择其中一个答案(例如理查德的答案)。

答案 4 :(得分:2)

我认为你差点使用UNION ALL代替UNION:

let loadCKEDITOR = require('bundle-loader?lazy!exports?window.CKEDITOR!ckeditor/ckeditor')

了解有关UNION a UNION ALL VS. UNION

的更多信息

答案 5 :(得分:2)

select sum(x.[STR]) as STCount, sum(x.[NCD]) as NCCount
from ECount  
pivot (count(DType) for DTypein ([NCD], [STR])) as x 

答案 6 :(得分:0)

更实际的方法可能是将每种类型的计数选为单独的记录并使用分组:

SELECT
   COUNT(*) AS TypeCount,
   Dtype
FROM ECount
WHERE Dtype IN ('STR', 'NCD')
  AND MONTH(Edate) = '07'
GROUP BY Dtype;