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

来源:互联网 发布:msiexec 卸载sql 编辑:程序博客网 时间:2024/05/08 22:10
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