隐藏值= 0但在总计算中计算其他列值的行 - sql2008

时间:2016-03-24 13:51:39

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

我有这样的表:(C1-C2 varchar(10),C3-Number int)

WaitingData
C1     C2     C3     Number
A      B      1       10
A      B      2       0
A      B      3       4
X      B      4       2

CompletedData
C1     C2     C3     Number
A      B      1       5
A      B      2       2
A      B      3       0
X      B      4       12

我使用下面的查询来表示数据:

Select wd.C1,wd.C2,wd.C3,wd.Number as NW,cdd.Number as NC
into #AllData
from (Select C1,C2,C3,sum(Number) from WaitingData group by C1,C2,C3) wd
outer apply (Select C1,C2,C3,sum(Number) 
             from CompletedData cd
             where wd.C1=cd.C1 and wd.C2=cd.C2 and wd.C3=cd.C3
            ) cdd


Select * from #AllData
union
Select C1='Total',C2='Total',C3=-1, sum(NW),sum(NW)
from #AllData

这给了我一个输出:

C1      C2      C3     NW     NC
A       B       1      10     5
A       B       2      0      2
A       B       3      4      0
X       B       4      2      12 
Total   Total   -1     16     19

但是,我想隐藏没有NW但在计算Total行时计算其相关值的行(参见下面的NC)。我想要的输出就像:

C1      C2      C3     NW     NC
A       B       1      10     5
A       B       3      4      0
X       B       4      2      12 
Total   Total   -1     16     19

我找不到像这样提供输出的方法。任何帮助都会非常感激!

------------------------------ EDIT ------------- --------------------------

------------------------------ EDIT ------------- --------------------------

当我在下表中有数据时,外部应用不能像我想的那样工作,它不包含数据A B 2.

WaitingData

C1     C2     C3     Number
A      B      1       10
A      B      3       4
X      B      4       2

CompletedData
C1     C2     C3     Number
A      B      1       5
A      B      2       2
X      B      4       12

输出结果如下:

C1      C2      C3     NW     NC
A       B       1      10     5
A       B       3      4      NULL
X       B       4      2      12 
Total   Total   -1     16     17

在这种情况下,除了插入CompletedData包含的所有记录但WaitingData之外,我可以做什么来计算最终结果为{2}的“2”NC值并将NC视为19而不是17? (需要一种有效的方式)

2 个答案:

答案 0 :(得分:2)

用另外一个选择并排除NW = 0的行来包装最终结果。

select * from
(
Select * from #AllData
union
Select C1='Total',C2='Total',C3=-1, sum(NW),sum(NC)
from #AllData
) t
where NW <> 0

编辑:使用full join从两个表中获取所有值。

with t as
(select coalesce(w.c1,c.c1) as c1,coalesce(w.c2,c.c2) as c2,coalesce(w.c3,c.c3) as c3
, coalesce(w.number,0) as nw , coalesce(c.number,0) as nc
from waitingdata w
full join completeddata c on w.c1 = c.c1 and w.c2=c.c2 and w.c3=c.c3) 
select * from 
(select * from t 
union all
Select C1='Total',C2='Total',C3=-1, sum(NW),sum(NC)
from t) x where nw <> 0

答案 1 :(得分:0)

您可以使用UNION运算符在一个查询中执行所有这些操作,无需临时表,中间结果,子查询或ROLLUP

SELECT
    WD.C1,
    WD.C2,
    WD.C3,
    SUM(WD.Number) AS NW,
    SUM(CD.Number) AS NC
FROM
    dbo.WaitingData WD
LEFT OUTER JOIN CompletedData CD ON
    CD.C1 = WD.C1 AND
    CD.C2 = WD.C2 AND
    CD.C3 = WD.C3
GROUP BY
    WD.C1,
    WD.C2,
    WD.C3
WITH ROLLUP
HAVING
    GROUPING_ID(WD.C1, WD.C2, WD.C3) IN (0, 7) AND
    SUM(WD.Number) <> 0