当前位置: 代码迷 >> Sql Server >> SQL,SQL,SQL!求一sql语句。解决思路
  详细解决方案

SQL,SQL,SQL!求一sql语句。解决思路

热度:96   发布时间:2016-04-27 19:19:22.0
SQL,SQL,SQL!!!求一sql语句。。。
表1
id bigsort sort city
1 离心机 低速自动平衡离心机 NULL
2 离心机 二手空分设备 NULL
3 离心机 塑料金属分离设备 NULL
4 压滤设备 机械及行业设备 NULL
5 压滤设备 化工设备压滤设备 NULL
6 压滤设备 白酒蒸馏设备 NULL
7 分离机 超临界CO2萃取设备 NULL
8 分离机 立体分离机 NULL
9 分离机 沙石分离机 NULL

表2
id city
1 北京
2 上海
3 南京


通过sql,得到下面的结果:即不同的分类下按照顺序插入表2的城市,


id bigsort sort city
1 离心机 低速自动平衡离心机 北京
2 离心机 二手空分设备 上海
3 离心机 塑料金属分离设备 南京
4 压滤设备 机械及行业设备 北京
5 压滤设备 化工设备压滤设备 上海
6 压滤设备 白酒蒸馏设备 南京
7 分离机 超临界CO2萃取设备 北京
8 分离机 立体分离机 上海
9 分离机 沙石分离机 南京


按bigsort的种类来分别插入各个城市。分数不多,希望大虾们多多支持哈。



------解决方案--------------------
--如果你两表ID都是序列增加.不出现断号等.
update tb1 set city = tb2.city
where (tb1.id - 1) % 3 = tb2.id - 1
------解决方案--------------------
SQL code
create table tb1(id int,city varchar(10))insert into tb1 values(1 , null)insert into tb1 values(2 , null)insert into tb1 values(3 , null)insert into tb1 values(4 , null)insert into tb1 values(5 , null)insert into tb1 values(6 , null)insert into tb1 values(7 , null)insert into tb1 values(8 , null)insert into tb1 values(9 , null)create table tb2(id int,city varchar(10))insert into tb2 values(1 ,'北京')insert into tb2 values(2 ,'上海')insert into tb2 values(3 ,'南京')goupdate tb1 set city = tb2.city from tb1 , tb2where (tb1.id - 1) % 3  = tb2.id - 1select * from tb1drop table tb1 , tb2/*id          city       ----------- ---------- 1           北京2           上海3           南京4           北京5           上海6           南京7           北京8           上海9           南京(所影响的行数为 9 行)*/
------解决方案--------------------
--如果你的序号不是自增一,出现断号
--sql 2000用子查询.
SQL code
create table tb1(id int,city varchar(10))insert into tb1 values(1 , null)insert into tb1 values(2 , null)insert into tb1 values(3 , null)insert into tb1 values(4 , null)insert into tb1 values(5 , null)insert into tb1 values(6 , null)insert into tb1 values(7 , null)insert into tb1 values(8 , null)insert into tb1 values(9 , null)create table tb2(id int,city varchar(10))insert into tb2 values(1 ,'北京')insert into tb2 values(2 ,'上海')insert into tb2 values(3 ,'南京')goupdate tb1 set city = tb2.city from tb1 , tb2,(select t.* , px=(select count(1) from tb1 where id < t.id) from tb1 t) tb3,(select t.* , px=(select count(1) from tb2 where id < t.id) from tb2 t) tb4where tb1.id = tb3.id and tb2.id = tb4.id and(tb3.px - 1) % 3  = tb4.px - 1select * from tb1drop table tb1 , tb2/*id          city       ----------- ---------- 1           北京2           上海3           南京4           NULL5           上海6           南京7           NULL8           上海9           南京(所影响的行数为 9 行)*/
  相关解决方案