如何修复此SQL GROUP BY查询?

时间:2009-12-03 10:50:39

标签: sql tsql sql-server-2000

我有以下查询:

SELECT 
    dev.DeviceName, Count(dom.DomainID) AS CountOfDomains 
FROM 
    tblDevices dev 
JOIN 
    tblIPNumbers ip ON dev.DeviceName = ip.ServerName 
JOIN 
    tblDomains dom ON dom.IPNumberID = ip.IPNumberID  
WHERE 
    dom.PointerTo=0 
    AND dev.DeviceType='3' 
    AND (dev.[System]='32' OR dev.[System]='33') 
    AND dom.ClosedDate IS NULL AND dev.Active=1 
GROUP BY 
    dev.DeviceName 
ORDER BY 
    Count(dom.DomainID)

表格如下:

tblDomains
==========
DomainID        int
IPNumberID      int
ClosedDate      datetime
PointerTo       int

tblIPNumbers
============
IPNumberID      int
ServerName      varchar(200)

tblDevices
==========
DeviceID        int
DeviceName      varchar(200)
System          varchar(10)
DeviceType      varchar(10)
Active          bit

示例数据:

tblDomains:
===========
DomainID: 1234  IPNumberID: 1000    ClosedDate: NULL   PointerTo: 0

tblIPNumbers:
=============
IPNumberID: 1000  ServerName: WIN2008-01

tblDevices:
===========
DeviceID: 1    DeviceName: WIN2008-01     System: 32    Active: 1  DeviceType: 3

问题在于,如果tblDomains中没有与IPNumberID中的tblIPNumbers匹配的行,则不会返回任何行。在这种情况下,我希望查询为0返回Count(dom.DomainID) AS CountOfDomains的单行。

我尝试了LEFTRIGHT联接的各种组合,这似乎是一个简单的问题,但我的SQL-fu今天很低。

3 个答案:

答案 0 :(得分:1)

将您的JOIN更改为LEFT JOIN,它们也会包含不匹配的记录。

答案 1 :(得分:1)

您应该使用LEFT JOIN而不是JOIN,并且还要注意当LEFT JOIN在右表中找不到匹配的行时,它会返回{{ 1}} s表示右表中的任何字段。

这意味着您的问题来自以非NULL安全方式引用WHERE的{​​{1}}条款,这将有效地消除dom.pointerto的好处。

答案 2 :(得分:0)

尝试对表tbldomains使用外连接


SELECT  
    dev.DeviceName, Count(dom.DomainID) AS CountOfDomains  
FROM  
    tblDevices dev  
JOIN  
   tblIPNumbers ip ON dev.DeviceName = ip.ServerName  
outer JOIN  
   tblDomains dom ON dom.IPNumberID = ip.IPNumberID   
WHERE  
    dom.pointerto=0  
    AND dev.devicetype='3'  
    AND (dev.[System]='32' OR dev.[System]='33')  
    AND dom.ClosedDate IS NULL AND dev.active=1  
GROUP BY  
    dev.DeviceName  
ORDER BY  
    Count(dom.DomainID)