求合并表格SQL语句

img

表结构一致,那就直接 union 然后列转行啊,每个表追加一个描述字段,作为列转行的列名即可


;with 表一(机构,监管指标数值) as (
    select 'a',0.6
    union all select 'b',0.8
    union all select 'c',0.3
    union all select 'd',0.3
    union all select 'e',0.3
),表二(机构,监管指标数值) as (
    select 'a',0.6
    union all select 'b',0.8
    union all select 'c',0.3
    union all select 'd',0.3
    union all select 'e',0.3
    union all select 'f',0.3
    union all select 'g',0.3
),表三(机构,监管指标数值) as (
    select 'a',0.6
    union all select 'b',0.8
    union all select 'c',0.3
    union all select 'd',0.3
    union all select 'e',0.3
    union all select 'f',0.3
    union all select 'g',0.3
),表十二(机构,监管指标数值) as (
    select 'a',0.6
    union all select 'd',0.3
    union all select 'e',0.3
    union all select 'f',0.3
    union all select 'g',0.3
)
select * from (
    select *,'2019年1月末' as mon from 表一
    union all select *,'2019年2月末' from 表二
    union all select *,'2019年3月末' from 表三
    union all select *,'2019年12月末' from 表十二
) a
pivot(max(监管指标数值) for mon in ([20191月末],[20192月末],[20193月末],[20194月末],[20195月末],[20196月末],[20197月末],[20198月末],[20199月末],[201910月末],[201911月末],[201912月末])) p 

img

我的测试数据表没弄那么多,你自己继续union即可

select m.机构名称,b1.指标 as 1月,b2.指标 as 2月,b3.指标 as 3from
(select 机构名称 from b1 union select 机构名称 from b2 union select 机构名称 from b3
)m left join b1 on b1.机构名称=m.机构名称
left b2 on b2.机构名称=m.机构名称
left b3 on b3.机构名称=m.机构名称
order by m.机构名称

用直接连接查询不就可以了吗