路线查询

表table_A:
  路线代码 起点 终点 起点桩号 终点桩号  
  Y440608 大湾 石柱 0.56 2.35  
  Y440608 石柱 观音桥 2.35 8.52
  Y440608 观音桥 芦溪 8.52 11.98
  Y440605 龙桥 磙子河 36.58 56.32

现在要写一条sql 让结果这样
  路线代码 起点 终点 起点桩号 终点桩号  
  Y440608 大湾 芦溪 0.56 11.98
  Y440605 龙桥 磙子河 36.58 56.32
问题分析:
1、典型的自联接问题;
2、首先查找同一编码下的起点最小值和最大值的两条记录;
3、选择同一编码下,最小的起点和最大的终点值,自关联出一条记录;
4、使用min和max函数,同时使用联接语句或EXISTS语句。
create table table_A(路线代码 varchar(10),起点 varchar(10),终点 varchar(10),起点桩号 decimal(18,2),终点桩号 decimal(18,2))
insert into table_a values('Y440608', '大湾'  , '石柱'  , 0.56  ,2.35)
insert into table_a values('Y440608', '石柱'  , '观音桥', 2.35  ,8.52)
insert into table_a values('Y440608', '观音桥', '芦溪'  , 8.52  ,11.98)
insert into table_a values('Y440605', '龙桥'  , '磙子河', 36.58 ,56.32)
go

select 路线代码,max(起点) 起点,max(终点) 终点,max(起点桩号) 起点桩号,max(终点桩号) 终点桩号 from
(
select t.路线代码,
       起点 = (case when not exists (select 1 from table_a where 路线代码 = t.路线代码 and 终点 = t.起点) then 起点 end),
       终点 = (case when not exists (select 1 from table_a where 路线代码 = t.路线代码 and 起点 = t.终点) then 终点 end),
       起点桩号 = (case when not exists (select 1 from table_a where 路线代码 = t.路线代码 and 终点 = t.起点) then 起点桩号 end),
       终点桩号 = (case when not exists (select 1 from table_a where 路线代码 = t.路线代码 and 起点 = t.终点) then 终点桩号 end)
from table_a t
) m
group by 路线代码

drop table table_a

/*
路线代码       起点         终点         起点桩号                 终点桩号                 
---------- ---------- ---------- -------------------- -------------------- 
Y440605    龙桥         磙子河        36.58                56.32
Y440608    大湾         芦溪         .56                  11.98

(所影响的行数为 2 行)
posted @ 2011-05-12 06:01  geass..  阅读(434)  评论(0编辑  收藏  举报