- 爱易网页
-
MSSQL教程
- 很菜的有关问题,求一SQL语句
日期:2014-05-19 浏览次数:20773 次
很菜的问题,求一SQL语句。
有4个表,分别为:
TA TB TC TD
ID1 客户名称 ID2 供应商 ID3 加工商 ID4 交付单位
1 大众 1 YQ 1 TQS 1 DELL
2 万联 2 MC 2 KL
3 ST 3 DY
说明:ID1=ID2=ID3=ID4=NO,且标记为唯一
数据的填充顺序依次为:TA、TB、TC、TD
现需要一SQL语句,要求输入NO后,显示该NO所对应的所有数据,没有数据的显示空白。
如输入1(即NO=1),查询结果为:
ID1 客户名称 ID2 供应商 ID3 加工商 ID4 交付单位
1 大众 1 YQ 1 TQS 1 DELL
输入3(即NO=3),查询结果为:
ID1 客户名称 ID2 供应商 ID3 加工商 ID4 交付单位
3 ST 3 DY
请大虾们帮帮忙,不胜感谢。
------解决方案--------------------
select max(id1) as id1,max(客户名称) as 客户名称,
max(id2) as id2,max(供应商) as 供应商,
max(id3) as id3,max(加工商) as 加工商,
max(id4) as id4,max(交付单位) as 交付单位
from (
select id1,客户名称,
case(null as int) as ID2,cast(null as varchar(40)) as 供应商,
case(null as int) as ID3,cast(null as varchar(40)) as 加工商,
case(null as int) as ID4,cast(null as varchar(40)) as 交付单位
from TA
where id1=3
union all
select null as id1,null as 客户名称,
ID2,供应商,
case(null as int) as ID3,cast(null as varchar(40)) as 加工商,
case(null as int) as ID4,cast(null as varchar(40)) as 交付单位
from TB
where id2=3
union all
select null as id1,null as 客户名称,
null as ID2,null as 供应商,
ID3,加工商,
case(null as int) as ID4,cast(null as varchar(40)) as 交付单位
from TC
where id3=3
union all
select null as id1,null as 客户名称,
null as ID2,null as 供应商,
null as ID3,null as 加工商,
ID4,交付单位
from TD
where id4=3
) as t
------解决方案--------------------
drop table TA,TB,TC,TD
go
create table TA(ID1 INT,客户名称 varchar(10))
create table TB(ID2 int,供应商 varchar(10))
create table TC(ID3 int,加工商 varchar(10))
create table TD(ID4 int,交付单位 varchar(10))
insert into TA
select 1, '大众 '
union all select 2, '万联 '