已知T1、T2、T3表,其中T1、T2项目名称相同,T2与T3标准名称相同,求怎样得到T4表?求SQL语句,谢谢
T1表
项目名称
项目1
项目2
项目5
T2表
项目名称 标准名称
项目1 标准1
项目1 标准2
项目2 标准3
项目2 标准4
T3表
标准名称 数量
标准1 100
标准2 300
标准3 500
如何得到T4表
项目名称 数量
项目1 400
项目2 500
项目5 0
------解决思路----------------------
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-12-01 13:40:09
-- Version:
-- Microsoft SQL Server 2014 - 12.0.2254.0 (X64)
-- Jul 25 2014 18:52:51
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.4 <X64> (Build 9860: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[T1]
if object_id('[T1]') is not null drop table [T1]
go
create table [T1]([项目名称] varchar(5))
insert [T1]
select '项目1' union all
select '项目2' union all
select '项目5'
--> 测试数据:[T2]
if object_id('[T2]') is not null drop table [T2]
go
create table [T2]([项目名称] varchar(5),[标准名称] varchar(5))
insert [T2]
select '项目1','标准1' union all
select '项目1','标准2' union all
select '项目2','标准3' union all
select '项目2','标准4'
--> 测试数据:[T3]
if object_id('[T3]') is not null drop table [T3]
go
create table [T3]([标准名称] varchar(5),[数量] int)
insert [T3]
select '标准1',100 union all
select '标准2',300 union all
select '标准3',500
--------------开始查询--------------------------
select a.项目名称,sum(isnull(c.数量,0))数量
from [T1] a full join [T2] b on a.项目名称=b.项目名称
full join [T3] c on b.标准名称=c.标准名称
group by a.项目名称
----------------结果----------------------------
/*
项目名称 数量
----- -----------
项目1 400
项目2 500
项目5 0
*/