相关子查询!!!!!!!!!!

zxy(6691587010:40:39(表名为: t)
有个表,属性为:编号 客户  订货产品
                                   
1    无锡  钢材
                                   
2    无锡  汽配件
                                   
3    无锡  电线
                                   
4    北京  烤鸭
                                   
5    北京  湖南鱼
                                   
6    重庆  火锅
               
 
zxy(
6691587010:41:53
要求如下:查询显示为
                编号 客户  订货产品
                
1    无锡     钢材
                
2                 汽配件
                
3                 电线
                
4    北京     烤鸭
                
5                湖南鱼
                
6    重庆    火锅


select                                   --------------------这种语句的性能最好了,我看了查询分析执行计划
    a.编号,
    客户
=case when exists(select 1 from t where 客户=a.客户 and 编号<a.编号) then '' else a.客户 end,
    客户订货产品
from
    t a
order by
    a.编号


注:
1,case 的语句先运行出一个结果集,放到一个临时表中,
2,然后从from t a 和上面的临时表进行匹配,找出符合条件的结果集。



------------------------------------------------------------------------------------------------------------------------------
--
--------------------------------------------------------------------------------------------------------------------------
select * into #t1 from t          
update #t
set col1=''
from #t,
(
select id from #t where id not in (select min(id) from #t x  group by col1)) #b ---- 加与不加 where 结果集一样的
where #t.id = #b.id

select * from #t

drop table #t ----显式删除临时表


----------------------------------------------------------------------
--
---------------------------------------------------------------------
--
创建测试数据
declare @t table (编号 int, 客户 varchar(100),订货产品 varchar(100))

insert into @t
select 1,'无锡','钢材' union all
select 2,'无锡','汽配件' union all
select 3,'无锡','电线' union all
select 4,'北京','烤鸭' union all
select 5,'北京','湖南鱼' union all
select 6,'重庆','火锅'

select * from @t

select 
    A.编号,
    
case when 编号=(select min(编号) from @t where 客户=A.客户) then A.客户 else '' end as 客户,
    A.订货产品
from @t A
order by A.编号
-------------------------------------------------------------------------------
--
------------------------------------------------------------------------------
create table test
(
编号 
int identity(1,1),
客户 
varchar(10),
订货产品 
varchar(10)
)
insert test
select '无锡',  '钢材'   union all
select '无锡',  '汽配件' union all
select '无锡',  '电线'   union all
select '北京',  '烤鸭'   union all
select '北京',  '湖南鱼' union all
select '重庆',  '火锅'
select * from test



select 编号,客户,订货产品 from test where 编号 in(select
min(编号) from test group by 客户)
union all
select 编号,'',订货产品 from test where 编号 not in
(
select min(编号) from test group by 客户
order by 编号
drop table test
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值