Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL COUNT Rows Result in separate columns

Tags:

sql

sql-server

I currently use this to count all the number or rows in a table and it works well for what i need.

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

The only issue i have is i have to repeat this statement a lot while just changing a few things each time. I would like to Union these Selects but have the result show in a seperate column, the example below works getting the results but puts them all in the same column. Any ideas how to have them show in their own column one for STCount and 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

result would be,

STCount NCCount
  100     202
like image 937
Ryan Avatar asked Aug 01 '17 08:08

Ryan


3 Answers

You can do selects in the select clause and don't need a 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;
like image 71
Richard Avatar answered Sep 28 '22 16:09

Richard


You can use a 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
like image 22
TOUZENE Mohamed Wassim Avatar answered Sep 28 '22 15:09

TOUZENE Mohamed Wassim


SELECT (SELECT COUNT(*) AS STCount 
          FROM (SELECT Distinct DPoint, RNum 
                  FROM ECount  
                 WHERE DType = 'STR' AND Month(EDate) = '07')) AS STCount
       , (SELECT COUNT(*) AS NCCount 
           FROM (SELECT Distinct DPoint, RNum 
                   FROM ECount  
                  WHERE DType = 'NCD' AND Month(EDate) = '07')) AS NCCount
like image 27
RealCheeseLord Avatar answered Sep 28 '22 17:09

RealCheeseLord