SQL如果value为零,则不返回列

时间:2011-07-13 19:24:20

标签: sql sql-server sql-server-2005 tsql

此查询返回一行,其中包含“准备”,“处理”,“完成”,“失败”和“错误”列,每行都包含总计。有没有办法重写此查询,以便不返回总计为零的列?

我正在使用它来填充mschart控件,如果该类别有0个实例,我不会在图表上标记。

SELECT        
              SUM(CASE WHEN Status = 'R' THEN 1 ELSE 0 END) AS Ready,
              SUM(CASE WHEN Status = 'P' THEN 1 ELSE 0 END) AS Processing, 
              SUM(CASE WHEN Status = 'C' THEN 1 ELSE 0 END) AS Complete,
              SUM(CASE WHEN Status = 'F' THEN 1 ELSE 0 END) AS Failed,
              SUM(CASE WHEN Status = 'E' THEN 1 ELSE 0 END) AS Error
FROM  MailDefinition 

2 个答案:

答案 0 :(得分:5)

不,因为必须知道查询的形状(它包含的字段)。只有数据可以改变,这就是你应该寻找的东西。您可以根据列中的0null数据动态删除或隐藏标签。

答案 1 :(得分:1)

我要做的就是拿走你拥有的东西,将它扔进一个开启的东西,然后删除所有的0条记录。

select
    Type, 
    Sum
from
(
    SELECT                       
        SUM(CASE WHEN Status = 'R' THEN 1 ELSE 0 END) AS Ready,               
        SUM(CASE WHEN Status = 'P' THEN 1 ELSE 0 END) AS Processing,                
        SUM(CASE WHEN Status = 'C' THEN 1 ELSE 0 END) AS Complete,               
        SUM(CASE WHEN Status = 'F' THEN 1 ELSE 0 END) AS Failed,               
        SUM(CASE WHEN Status = 'E' THEN 1 ELSE 0 END) AS Error 
FROM  MailDefinition 
) a
unpivot
(
     Sum for Type in ([Ready],[Processing],[Complete],[Failed],[Error])
) u
where Sum>0

当然,这需要更改你的图表。