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
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;
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With