如何避免SQL Server中一列的数据

时间:2014-05-28 13:30:50

标签: sql sql-server sql-server-2008-r2

我有以下查询,这是两个表的连接,你可以看到从结果我想避免来自一列的数据。从结果集下面我想避免其他行

IncidentCategory             No_Incident

Near Miss                  25
Road Events               129
Service Strike                150
Other                         Null  


SELECT BT.Name AS IncidentCategory, SUM(IR.ID) AS No_Incident  
From BBTypes BT LEFT JOIN  
     IncidentReports IR  
     ON BT.ID = IR.BbType AND
        IR.WbsElementId =  23 
GROUP BY BT.Name                
ORder By BT.Name DESC

3 个答案:

答案 0 :(得分:1)

在您的查询中,您使用GROUP BY,因此最好使用HAVING COUNT来提升您的查询效果。

HAVING COUNT(IR.ID)> 0是避免No_Incident列中的空行。

SELECT BT.Name AS IncidentCategory, SUM(IR.ID) AS No_Incident  
From BBTypes BT LEFT JOIN  
     IncidentReports IR  
     ON BT.ID = IR.BbType AND
        IR.WbsElementId =  23 
GROUP BY BT.Name       
HAVING COUNT(IR.ID)>0         
ORDER BY BT.Name DESC

答案 1 :(得分:0)

如果您尝试忽略NULL行,请使用inner join代替外部联接:

SELECT BT.Name AS IncidentCategory, SUM(IR.ID) AS No_Incident  
From BBTypes BT JOIN  
     IncidentReports IR  
     ON BT.ID = IR.BbType AND
        IR.WbsElementId =  23 
GROUP BY BT.Name                
ORder By BT.Name DESC;

执行id列的总和看起来很奇怪。我猜你真的想要count()

SELECT BT.Name AS IncidentCategory, COUNT(IR.ID) AS No_Incident  
From BBTypes BT JOIN  
     IncidentReports IR  
     ON BT.ID = IR.BbType AND
        IR.WbsElementId =  23 
GROUP BY BT.Name                
ORder By BT.Name DESC;

答案 2 :(得分:0)

尝试添加

where BT.Name <> 'Other'