1

我正在创建一个存储过程,从几个不同的表中提取聚合总和值。另外,查询很简单,使用不同的过滤器。

查询需要连接在一起,如下所示:

select distinct(bus_name), sum(act) as 'totrev', sum(budget) as 'budget rev' 
from finance
where year = '2011' 
and type_desc = 'rev'
group by bus_code, bus_name
order by bus_name asc

select distinct(bus_name), sum(act) as 'totalexp', sum(budget) as 'budget exp' 
from finance
where year = '2011' 
and type_desc = 'exp'
group by bus_code, bus_name
order by bus_name asc

select distinct(bus_name), sum(end_balance) as 'total assets' 
from Balance
where year = '2011' 
and type_desc = 'assets'
group by bus_code, bus_name
order by bus_name asc

select distinct(bus_name), sum(end_balance) as 'Cash' 
from Balance
where year = '2011' 
and type_desc = 'equity'
group by bus_code, bus_name
order by bus_name asc

select bus_code, bus_name, count(bus_code) as '#of bldgs'
from building
group by bus_code, bus_name
order by bus_name asc

我希望合并/连接所有要在一个表中查看的列。财务
表列 = bus_code、bus_name、# of bldgs、tot_rev、budget_rev、totalexp、budget exp、总资产、现金

4

2 回答 2

1

通过使用嵌套查询尝试这样的事情:

SELECT T5.bus_code, T5.bus_name, T5.[# of bldgs], T1.tot_rev, T1.budget_rev, T2.totalexp, T2.[budget exp], T3.[total assets], T4.cash
FROM
    (
    select distinct(bus_name), sum(act) as 'totrev', sum(budget) as 'budget rev' 
    from finance
    where year = '2011' 
    and type_desc = 'rev'
    group by bus_code, bus_name
    order by bus_name asc
    ) T1 INNER JOIN
    (
    select distinct(bus_name), sum(act) as 'totalexp', sum(budget) as 'budget exp' 
    from finance
    where year = '2011' 
    and type_desc = 'exp'
    group by bus_code, bus_name
    order by bus_name asc
    ) T2 ON T1.bus_name = T2.bus_name
    INNER JOIN
    (
    select distinct(bus_name), sum(end_balance) as 'total assets' 
    from Balance
    where year = '2011' 
    and type_desc = 'assets'
    group by bus_code, bus_name
    order by bus_name asc
    ) T3 ON T2.bus_name = T3.bus_name
    INNER JOIN
    (
    select distinct(bus_name), sum(end_balance) as 'Cash' 
    from Balance
    where year = '2011' 
    and type_desc = 'equity'
    group by bus_code, bus_name
    order by bus_name asc
    ) T4 ON T3.bus_name = T4.bus_name
    INNER JOIN
    (
    select bus_code, bus_name, count(bus_code) as '#of bldgs'
    from building
    group by bus_code, bus_name
    order by bus_name asc
    ) T5 ON T4.bus_name = T5.bus_name

我假设内部联接,但如果其中一些没有特定业务的条目,您可能需要使用外部联接。但是一般的技术是一样的。

于 2013-01-25T19:05:13.997 回答
1

如果您的 SQL 支持 CASE 表达式,您可以使用它们为每种类型创建“虚拟”字段,然后将它们汇总。

select bus_code, bus_name
 ,sum(case when type_desc = 'rev' then act else 0 end) as 'totrev'
 ,sum(case when type_desc = 'rev' then budgetelse 0 end) as 'budget rev' 
 ,sum(case when type_desc = 'exp' then act else 0 end) as 'totexp'
 ,sum(case when type_desc = 'exp' then budgetelse 0 end) as 'budget exp' 
 ... ... etc.
from finance
where year = '2011' 
group by bus_code, bus_name
order by bus_name asc

最后一个(建筑)表可以简单地连接到这个,在总线代码上

于 2013-01-25T20:03:53.127 回答