当前位置: 代码迷 >> Sql Server >> 两张表合并结果,性能较好的sql
  详细解决方案

两张表合并结果,性能较好的sql

热度:36   发布时间:2016-04-24 09:59:07.0
两张表合并结果,求一个性能较好的sql
表A:

C1     C2      C3        C4
a        b         c          10
b        c         d            5
e        a         f           12
a        b         c          11
e        a         f            8
f         e         b          33
b        e         h          50

表B:

C1     C2      C3        C5
e        a         f          10
b        c         d            5
e        a         f           12
a        b         c          11
b        c         d           8


合并成表C:

C1     C2      C3        C4       C5
a        b         c          21        11
b        c         d            5        13
e        a         f           20        21
f         e         b          33
b        e         h          50


能想到的就是先group表A到临时表T,然后遍历表C,根据条件将B group后的结果插入C。。。不过貌似太low了有点,性能也差
所以求教一个性能好的sql
------解决思路----------------------
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(發糞塗牆)
-- Date    :2014-09-29 12:23:46
-- Version:
--      Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
-- May 14 2014 18:34:29 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go 
create table [A]([C1] varchar(1),[C2] varchar(1),[C3] varchar(1),[C4] int)
insert [A]
select 'a','b','c',10 union all
select 'b','c','d',5 union all
select 'e','a','f',12 union all
select 'a','b','c',11 union all
select 'e','a','f',8 union all
select 'f','e','b',33 union all
select 'b','e','h',50
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go 
create table [B]([C1] varchar(1),[C2] varchar(1),[C3] varchar(1),[C5] int)
insert [B]
select 'e','a','f',10 union all
select 'b','c','d',5 union all
select 'e','a','f',12 union all
select 'a','b','c',11 union all
select 'b','c','d',8
--------------开始查询--------------------------


SELECT c1,c2,c3,SUM(c4)c4,SUM(c5)c5
FROM (
select C1  ,   C2  ,    C3,        C4    , 0 AS   C5 from [A]
UNION ALL 
select C1  ,   C2  ,    C3,   0 AS      C4    ,  C5 from [B])a
  相关解决方案