路线查询

表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 行)

转载于:https://www.cnblogs.com/geass/archive/2011/05/12/2043949.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值