将两个记录集合并为一个结果,包括NULL值

时间:2015-02-06 16:03:11

标签: join sql-server-2012 group-by null

我有如下的sql脚本:

select a.Program,a.COUNTS_OPEN,b.COUNTS_CLOSE
from 
(select Program, count(ISNULL(Program,'UNKNOWN')) COUNTS_OPEN
from table_a
WHERE (SUBMITDATE > CONVERT(datetime, '2014-08-31 23:59:59.000') and SUBMITDATE < CONVERT(datetime, '2014-10-01 00:00:00.000') ) 
group by Program) as a 

full JOIN

(
select Program,count(ISNULL(Program,'UNKNOWN')) COUNTS_CLOSE 
from table_a
WHERE  (STATUS='Closed' and UPDATEDATE > CONVERT(datetime, '2014-08-31 23:59:59.000') and UPDATEDATE < CONVERT(datetime, '2014-10-01 00:00:00.000') ) 
group by Program) as b
on a.Program= b.Program

并且在结果中有两行NULL,但我希望一行为NULL,因为它按程序分组。这是结果集:

Program COUNTS_OPEN COUNTS_CLOSE
NULL        NULL              8
NULL        18            NULL
ProgramA    253           205
ProgramB    2              2
ProgramC    123            109

代替两行NULL,我需要一行如:

  Program   COUNTS_OPEN COUNTS_CLOSE
    NULL        18            8
    ProgramA    253           205
    ProgramB    2              2
    ProgramC    123            109

无法弄清楚如何正确加入。

1 个答案:

答案 0 :(得分:0)

在不知道你的表结构的情况下这是一个猜测,但我认为这个使用条件聚合的查询应该能达到你想要的效果:

SELECT 
    Program, -- replace with ISNULL(Program,'UNKNOWN'), if you want UNKNOWN instead of NULL
    COUNTS_OPEN   = SUM(case when (SUBMITDATE > CONVERT(datetime, '2014-08-31 23:59:59.000') and SUBMITDATE < CONVERT(datetime, '2014-10-01 00:00:00.000') ) then 1 else 0 end), 
    COUNTS_CLOSED = SUM(case when (STATUS='Closed' and UPDATEDATE > CONVERT(datetime, '2014-08-31 23:59:59.000') and UPDATEDATE < CONVERT(datetime, '2014-10-01 00:00:00.000') ) then 1 else 0 end) 
FROM table_a
GROUP BY program