求助多表汇总sql 语句

sql server 中有四个表,
A,B,C,D ,
四表中有相同字段为“单位”值为“单位一”。
其他相同字段“金额”“单价”“合计”
写一语句汇总 四表中的 字段“金额” “小计”
select 单位,sum(金额),sum(小计)
from
(
select 单位,金额,合计 from A
union all
select 单位,金额,合计 from B
union all
select 单位,金额,合计 from C
union all
select 单位,金额,合计 from D
)tt group by 单位

请问上面语句)后面的 tt 是什么意思 ,换其他字母也可以,但不加却不行?

select 单位,sum(金额),sum(小计)
from
(
select 单位,金额,合计 from A
union all
select 单位,金额,合计 from B
union all
select 单位,金额,合计 from C
union all
select 单位,金额,合计 from D
)tt group by 单位
可通过union all 把4表合并。
tt 就是给括号中的查询结果起个别名,可以随便起,意思就是把查询结果作为一个表来处理,子查询中经常用到这种操作。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-01-11
select sum(金额) as 总金额, sum(合计) as 总计 from
(select 单位,金额,合计 from A
union all
select 单位,金额,合计 from B
union all
select 单位,金额,合计 from C
union all
select 单位,金额,合计 from D) as all

如果,要按单位分组的话,再加上group by子句:
select 单位, sum(金额) as 总金额, sum(合计) as 总计 from
(select 单位,金额,合计 from A
union all
select 单位,金额,合计 from B
union all
select 单位,金额,合计 from C
union all
select 单位,金额,合计 from D) as all
group by 单位
第2个回答  2011-01-11
select 单位,sum(合计) as 合计 from (
select 单位,单价,合计 from a union all
select 单位,单价,合计 from b union all
select 单位,单价,合计 from c union all
select 单位,单价,合计 from c
) t
group by 单位
order by 单位
第3个回答  2011-01-11
select all_four.单位,sum(all_four.金额) from (select 单位,金额 from A union select 单位,金额 from B union select 单位,金额 from C union select 单位,金额 from D) all_four
group by all_four.单位
相似回答