sql数据库表的高级查询
发布网友
发布时间:2022-04-25 00:55
我来回答
共3个回答
热心网友
时间:2022-04-08 04:54
if(OBJECT_ID('tempdb..#view_class') > 0)
drop table #view_class
--将只有一个记录的数据放入临时表
select classname,cweeks,ctimes,roomname into #view_class from view_class
where CHARINDEX(cweeks,',') = 0
--将有2条记录的数据拆分插入临时表
insert into #view_class
select classname,substring(cweeks,1,charindex(',',cweeks)-1),substring(cweeks,1,charindex(',',ctimes)-1),roomname from view_class
where CHARINDEX(cweeks,',') > 0
union all
select classname,substring(cweeks,charindex(',',cweeks)+1,LEN(cweeks)),substring(cweeks,charindex(',',ctimes)+1,LEN(ctimes)),roomname from view_class
where CHARINDEX(cweeks,',') > 0
if(OBJECT_ID('tempdb..#view_class_1') > 0)
drop table #view_class_1
--将临时表按照cweeks分组排序,并建立分组排序的序号插入新的临时表
select ROW_NUMBER() over(partition by cweeks order by cweeks) id,* #view_class_1 from #view_class追问我捣鼓了一下,发现没成功.....我观察了,我能理解你的思路了,我看看貌似也觉得逻辑没啥问题,只是发现我select 这个临时表,结果跟原表结果一样的...没见有新的添加的数据
我顶....CHARINDEX(cweeks,',')哥们 你把这个写反了.... 可以用了
追答不好意思,没注意,纯手打的
热心网友
时间:2022-04-08 06:12
先给你第一步,获取拆分结果,substring没仔细数,你自己稍微调整一下
select ClassID,ClassName,CWeeks,CTimes,RoomName from view_class where len(CWeeks)=2
union
select ClassID,ClassName,substring(CWeeks,1,2),substring(CTimes,1,15),RoomName from view_class where len(CWeeks)=5
union
select ClassID,ClassName,substring(CWeeks,4,2),substring(CTimes,17,15),RoomName from view_class where len(CWeeks)=5
得到这个结果之后,再去排序应该很简单了,自己就能搞定哈?!
热心网友
时间:2022-04-08 07:47
单独一条SQL搞不定的(根据CWeeks长度来分可能是一种方式), 需要函数配合将CWeeks的值分解成table.