这里是详细信息
TBL1
rec_id, rec_amount, rec_date
1 1500 1/1/2011
2 4500 1/1/2011
3 500 1/1/2011
4 15000 1/1/2011
5 7500 1/1/2011
TBL2
vouc_id vouc_amount pay_date
1 15000 1/1/2011
2 750.50 1/1/2011
3 560 1/1/2011
TBL3
don_id d_amount d_date
1 1500 1/1/2011
2 2000 1/1/2011
我在单个查询sum(rec_amount) from tbl1
中需要sum(vouc_amount) from tbl2
和sum(d_amount) from tbl3
以及where date = 1/1/2011
。任何身体可以帮助我吗?
答案 0 :(得分:2)
在表之间使用union all并在
之上执行SUM例如
SELECT SUM(TheAmount)
FROM(
SELECT rec_amount AS TheAmount
FROM tbl1
WHERE rec_date = '20110101'
UNION ALL
SELECT vouc_amount
FROM tbl2
WHERE pay_date = '20110101'
UNION ALL
SELECT d_amount
FROM tbl3
WHERE d_date = '20110101') x
或彼此相邻
SELECT SUM(rec_amount) AS tbl1Amount,(SELECT SUM(vouc_amount)
FROM tbl2
WHERE pay_date = '20110101') AS tbl2Amount ,(SELECT SUM(d_amount)
FROM tbl3
WHERE d_date = '20110101') AS tbl3Amount
FROM tbl1
WHERE rec_date = '20110101'
答案 1 :(得分:1)
您可以为每列进行子选择。
declare @T1 table(rec_id int, rec_amount int, rec_date datetime)
declare @T2 table(vouc_id int, vouc_amount int, pay_date datetime)
declare @T3 table(don_id int, d_amount int, d_date datetime)
insert into @T1 values
(1, 1500 , '2011-01-01'),
(2, 4500 , '2011-01-01'),
(3, 500 , '2011-01-01'),
(4, 15000, '2011-01-01'),
(5, 7500 , '2011-01-01')
insert into @T2 values
(1, 15000, '2011-01-01'),
(2, 750 , '2011-01-01'),
(3, 560 , '2011-01-01')
insert into @T3 values
(1, 1500, '2011-01-01'),
(2, 2000, '2011-01-01')
select
(select sum(rec_amount)
from @T1
where rec_date = '2011-01-01'),
(select sum(vouc_amount)
from @T2
where pay_date = '2011-01-01'),
(select sum(d_amount)
from @T3
where d_date = '2011-01-01')