相关子查询!!!!!!!!!!
2006-10-08 19:28
274 查看
zxy(66915870) 10:40:39(表名为: t)
有个表,属性为:编号 客户 订货产品
1 无锡 钢材
2 无锡 汽配件
3 无锡 电线
4 北京 烤鸭
5 北京 湖南鱼
6 重庆 火锅
zxy(66915870) 10: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
相关文章推荐
- java 相关查询原理
- SQL查询相关技术-5.SQL操作
- AutoLISP查询圆弧的相关属性
- 看了群友的帖子,加深对相关子查询的理解!!!
- arcEngine开发之查询相关接口
- mysql 查询语句统计和查询缓存相关的状态值解疑答惑
- Oracle树查询及相关函数
- mysql的多表查询的相关知识点
- db2与表相关的存储过程查询
- PostgreSQL系统相关查询[1]
- Linux网络相关查询脚本
- Oracle查询表结构的一些相关语句
- oracle等待事件相关查询
- 如何通过maven官网查询相关依赖的具体代码和版本?
- Oracle连接查询,子查询(相关子查询,嵌套子查询)
- shell 进程查询相关的命令
- LINUX下相关硬件信息的查询
- sql时间查询相关
- ORACLE数据库、表空间、表的容量相关查询--1
- mysql子查询相关问题