Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to get COUNT when using EXCEPT

Tags:

sql

sql-server

SELECT 'COUNT=' + CONVERT(VARCHAR(64), COUNT(s.company)) AS sites 
FROM   site s 
WHERE  s.sitetype = 'om' 
       AND s.status = 1 
EXCEPT 
SELECT DISTINCT sg.company 
FROM   snmpmibdevice AS sdevice 
       JOIN site sg 
         ON sg.guid = sdevice.siteguid 
       JOIN snmpmibdata sdata 
         ON sdata.snmpmibdeviceguid = sdevice.snmpmibdeviceguid 
WHERE  sdata.sampletimestamp > Dateadd (mi, -15, Getutcdate()) 
       AND sg.sitetype = 'OM' 

Basically I am attempting to return a count of company names from this. If I remove the count and just select "S.Company" I will get 2 values (I would like "COUNT=2"), but with the count it comes up as 34 records (COUNT=34).

I would appreciate any help. Thanks!

like image 921
xnttx Avatar asked Mar 26 '12 15:03

xnttx


People also ask

Can we use count function in WHERE clause in SQL?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.

Can we use count with GROUP BY clause?

The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.

How does count (*) work in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


1 Answers

wrap the whole thing in a "select count(*) from ()"

SELECT 'COUNT=' + CONVERT(VARCHAR(64), COUNT(company)) AS sites 
FROM (

    SELECT s.company
    FROM   site s 
    WHERE  s.sitetype = 'om' 
           AND s.status = 1 
    EXCEPT 
    SELECT DISTINCT sg.company 
    FROM   snmpmibdevice AS sdevice 
           JOIN site sg 
             ON sg.guid = sdevice.siteguid 
           JOIN snmpmibdata sdata 
             ON sdata.snmpmibdeviceguid = sdevice.snmpmibdeviceguid 
    WHERE  sdata.sampletimestamp > Dateadd (mi, -15, Getutcdate()) 
           AND sg.sitetype = 'OM' 
) a
like image 186
Derek Kromm Avatar answered Nov 15 '22 00:11

Derek Kromm