2011-01-21 63 views
1
select sum(a.perdblnc), a.actindx 
from [CASH].[dbo].[GL00100] b 
    inner join [CASH].[dbo].[GL10111] a 
on b.actindx = a.actindx 
where b.actnumbr_1 = 1020 
group by a.actindx 

Return: 
42378.15000 41 
54072.64000 42 
31698.21000 43 
75552.65000 44 

select sum(a.perdblnc), a.actindx 
from [CASH].[dbo].[GL00100] b 
    inner join [CASH].[dbo].[GL10110] a 
on b.actindx = a.actindx 
where b.actnumbr_1 = 1020 
group by a.actindx 

Retuns: 
28711.94000 41 
53781.08000 42 
26281.17000 43 
69345.59000 44 

我需要合併它,以便它返回總和或兩個查詢。最終的結果應該是:梳理查詢

57423.88 41 
107562.16 42 
52562.34 43 
138691.18 44 

回答

2

你要總結工會...

select sum(u.t), u.actindx 
from (

select sum(a.perdblnc) as t, a.actindx 
from [CASH].[dbo].[GL00100] b 
    inner join [CASH].[dbo].[GL10111] a 
on b.actindx = a.actindx 
where b.actnumbr_1 = 1020 
group by a.actindx 

union all 

select sum(a.perdblnc), a.actindx 
from [CASH].[dbo].[GL00100] b 
    inner join [CASH].[dbo].[GL10110] a 
on b.actindx = a.actindx 
where b.actnumbr_1 = 1020 
group by a.actindx 

) u 
group by u.actindx 

union all是必需的極少數情況下有DUPLIC在2 GL表中吃了一筆。

1

您可以使用UNION加入結果集兩個(或更多)的查詢:

在一個更簡單的場景:

SELECT 'Anna' as Name, 18 as Age 
UNION 
SELECT 'Bob' as Name, 19 as Age 

結果:

# | NAME | AGE 
0 | Anna | 18 
1 | Bob | 19 
+0

呃,那麼你如何使用工會來解決這個特殊問題呢? – Andomar 2011-01-21 16:09:36

0

你試過類似的東西嗎? -

 
select sum(a.perdblnc) + sum(c.perdblnc), a.actindx 
from [CASH].[dbo].[GL00100] b 
    inner join [CASH].[dbo].[GL10111] a 
    inner join [CASH].[dbo].[GL10110] c 
on b.actindx = a.actindx 
where b.actnumbr_1 = 1020 
group by a.actindx 

3

既然你只總結一列,你可以使用像子查詢:

select act.actindx 
,  (select sum(a.perdblnc) from [CASH].[dbo].[GL10110] a 
     where a.actindx = act.actindx) + 
     (select sum(a.perdblnc) from [CASH].[dbo].[GL10111] b 
     where b.actindx = act.actindx) 
from [CASH].[dbo].[GL00100] act 
where act.actnumbr_1 = 1020 
group by 
     act.actindx 

如果你需要更多的列時,你通常會與子查詢的另一種形式去,如:

select act.actindx 
,  sub_a.total + sub_b.total 
from [CASH].[dbo].[GL00100] act 
left join 
     (
     select a.actindx 
     ,  sum(a.perdblnc) as total 
     from [CASH].[dbo].[GL10110] a 
     group by 
       a.actindx 
     ) sub_a 
on  a.actindx = act.actindx 
left join 
     (
     select b.actindx 
     ,  sum(b.perdblnc) as total 
     from [CASH].[dbo].[GL10111] b 
     group by 
       b.actindx 
     ) sub_b 
on  b.actindx = act.actindx 
where act.actnumbr_1 = 1020 
group by 
     act.actindx