SQL Group by不显示所有变量

时间:2014-02-17 10:30:50

标签: sql sql-server group-by

我从MSSQL数据库中获取一个列表。我在数据库表中有一个系统列表和材料。我想从日期范围中获得摘要。但是数据库只给出了非空的行。这是我的代码

select system_no AS 'SYSTEM NAME', 
       SUM(CASE WHEN (mat_2='AS') THEN mat_2_size END) as 'AS',
       SUM(CASE WHEN (mat_2='SS') THEN mat_2_size END) as 'SS',
       SUM(CASE WHEN (mat_2='CS') THEN mat_2_size END) as 'CS'
from fabrication_table 
where welding_date between '2014-02-03' and '2014-02-09' 
group by system_no 
UNION 
select 'TOTAL' as 'SYSTEM NAME',
       SUM(CASE WHEN (mat_2='AS') THEN mat_2_size END) as 'AS',
       SUM(CASE WHEN (mat_2='SS') THEN mat_2_size END) as 'SS',
       SUM(CASE WHEN (mat_2='CS') THEN mat_2_size END) as 'CS' 
from fabrication_table 
where welding_date between '2014-02-03' and '2014-02-09'

此查询的结果在

下面
SYSTEM NAME              AS      SS     CS
Auxiliary steam          NULL    NULL   6.75
Chemical dosing          NULL    10.00  NULL
Closed cooling water     NULL    1.50   193.75
Condensate               NULL    NULL   32.00
Demineralized water      NULL    34.00  NULL
Feedwater                NULL    NULL   6.00
Gases (N2, H2, CO2)      NULL    NULL   385.25
GT air intake anti-icing NULL    NULL   220.50
Main steam & by-pass     49.50   NULL   84.00
Seawater intake          NULL    27.50  NULL
ST drains                37.50   NULL   175.50
ST seals steam           NULL    2.25   175.00
TOTAL                    87.00   75.25  1278.75

但我的系统名称列表是:

Potable water
Service water
Seawater intake
Chemical dosing
Closed cooling water
GT interconnections
Feedwater
HRSG blowdown
Sampling
Fire fighting
GT Lube Oil
Auxiliary steam
Desalted water
Demineralized water
ST lube & seal oil
Main steam & by-pass
ST drains
GT air intake anti-icing
Condenser vacuum
ST seals steam
Condensate
Plant drainage
Filtered water
Compressed air
GT drainage
Fuel gas
Gases (N2, H2, CO2)

这是我的问题:我想列出所有变量,例如该查询未列出Fire Fighting但我想列出此类消防

Fire Fighting       NULL     NULL    NULL

2 个答案:

答案 0 :(得分:2)

默认情况下,Null会从聚合中删除。

尽量避免"归零"使用合并的值:

,SUM(CASE WHEN (mat_2='AS') THEN mat_2_size END) as 'AS' 

更改为:

,SUM(CASE WHEN (mat_2='AS') THEN coalesce(mat_2_size,0) END) as 'AS' 

答案 1 :(得分:-1)

我用这个代码块解决了我的问题

SELECT ISNULL(column,0) FROM...

它可以帮助我显示空变量