SQL:如何在使用EXCEPT时获取COUNT

时间:2012-03-26 15:29:41

标签: 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' 

基本上我试图从中返回公司名称的数量。如果我删除计数并只选择“S.Company”我会得到2个值(我想要“COUNT = 2”),但是计数它会出现34个记录(COUNT = 34)。

我将不胜感激任何帮助。谢谢!

1 个答案:

答案 0 :(得分:8)

将整个事物包装在“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