表t1,有列: 供应商 货号 生产数量
A 001 200
B 001 30
B 002 500
B 003 100
表t2 有列: 货号 订货数量
001 500
002 700
希望左连接成如下的形式:(t1 left join t2 on t1.货号=t2.货号)供应商 货号 订货数量 生产数量
A 001 500 200
B 001 - 30 (正常情况下,本行的订货数量也会被连接成500)
B 002 700 500
B 003 100
怎样去掉那行的数量置为null
A 001 200
B 001 30
B 002 500
B 003 100
表t2 有列: 货号 订货数量
001 500
002 700
希望左连接成如下的形式:(t1 left join t2 on t1.货号=t2.货号)供应商 货号 订货数量 生产数量
A 001 500 200
B 001 - 30 (正常情况下,本行的订货数量也会被连接成500)
B 002 700 500
B 003 100
怎样去掉那行的数量置为null
货号,
case when 生产数量=(select max(生产数量) from t1 where a.货号=t1.货号) then 订货数量 else NULL end as '订货数量',
生产数量
from t1 a
left join t2 on t1.货号=t2.货号
create table t2(货号 varchar(10),订货数量 int)insert into t1 select 'A' , '001' , 200 union all
select 'B' , '001' , 30 union all
select 'B' , '002' , 500 union all
select 'B' , '003' , 100
insert into t2 select '001' , 500 union all
select '002' , 700 select 供应商,t1.货号,订货数量,生产数量 from t1 left join t2 on t1.货号=t2.货号
-----
A 001 500 200
B 001 500 30
B 002 700 500
B NULL NULL 100
没有问题啊??
应为
供应商 货号 订货数量select t1.供应商,t1.货号,t2.订货数量,t1.生产数量 from t1 left join t2 on t1.货号=t2.货号 and t1.供应商=t2.供应商
a.货号,
case when 生产数量=(select max(生产数量) from t1 where a.货号=t1.货号) then 订货数量 else NULL end as '订货数量',
生产数量
from t1 a
left join t2 on a.货号=t2.货号
jacobsan(梅):我是想把第2行中的订货数量500,置为null。请详细看清问题。
先谢谢2位。希望能有更好的解决方法
go
create table t1(供应商 varchar(10),货号 varchar(10),生产数量 int)
insert into t1
select 'A','001',200
union all select 'B','001',30
union all select 'C','001',200
union all select 'B','002',500
union all select 'B','003',100create table t2(货号 varchar(10),订货数量 int)
insert into t2
select '001',500
union all select '002',700 alter table t1 add id int identity(1,1)select 供应商,
a.货号,
case when id=(select min(id) from t1 where a.货号=t1.货号) then 订货数量 else NULL end as '订货数量',
生产数量
from t1 a
left join t2 on a.货号=t2.货号
/*
供应商 货号 订货数量 生产数量
---------- ---------- ----------- -----------
A 001 500 200
B 001 NULL 30
C 001 NULL 200
B 002 700 500
B 003 NULL 100(所影响的行数为 5 行)
*/
create table t2(货号 varchar(10),订货数量 int)insert into t1 select 'A' , '001' , 200 union all
select 'B' , '001' , 30 union all
select 'B' , '002' , 500 union all
select 'B' , '003' , 100
insert into t2 select '001' , 500 union all
select '002' , 700 select 供应商,t1.货号,订货数量,生产数量 from t1 left join t2 on t1.货号=t2.货号
A 001 - 200
B 001 500 30
B 002 700 500
B 003 100 也就是你的分配策略是怎样的?或者说你的供应商的优先级别在哪里体现?
t1.供应商,
t1.货号,
case WHEN 供应商 = (select min(供应商) from t1 where t1.货号 = t2.货号) then t2.订货数量 else NULL END AS 订货数量,
t1.生产数量
from
t1 left join t2 on t1.货号 = t2.货号
不过表设计的有问题
目前看来gahade(与君共勉)加一个ID字段的方法只能是目前最好的解决方法了。
jyxhz(jyxhz):这里不存在供应商的优先级问题。我的本意是:有了t1,t2两上基表,我只是想查询出我需要的结果:即在订货数量这列里面,每个货号只能出现一次订货数量,但一个货号可能由2个以上供应商供货,所以结果里面会存允许存以重复的货号。明白我的意思吗?
zst126(皮皮):你说表设计有问题,你是否能提供一个更好的表设计范例。