请问实现以下功能SQL语句怎么写?

jianglf 2003-08-18 06:28:06
请问实现以下功能SQL语句怎么写?

表a的内容为:

id name changetime root father content sort
11 aa 2003-08-15 12:01 1 0 12345678 0
12 vb 2003-08-16 1:00 1 0 23423545 0
13 ff 2003-08-15 11:00 0 11 421433124 2
14 e2 2003-08-12 3:00 0 12 24324444 1
15 33 2003-08-17 13:00 1 0 22234354 0
16 21 2003-08-17 14:00 0 11 24231442 1


要取得的结果集为:

15 33 2003-08-17 13:00 1 0 22234354 0

12 vb 2003-08-16 1:00 1 0 23423545 0
14 e2 2003-08-12 3:00 0 12 24324444 1

11 aa 2003-08-15 12:01 1 0 12345678 0
16 21 2003-08-17 14:00 0 11 24231442 1
13 ff 2003-08-15 11:00 0 11 421433124 2


说明:将root=1 的按changetime降序取出,同时将father等于取出的ID的记录紧跟后面,并以sort排序

请问实现这样的功能SQL语句怎么写?谢谢
...全文
47 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
j9988 2003-08-18
  • 打赏
  • 举报
回复
主要是增加两个排序用的新列:
temp_datetime-FATHER的修改时间。
tempid-1为FATHER 2为CHILDREN

select (select changetime from tm where id=A.father)--让它的新增的temp_datetime列与FATHER一样。这样排序时才相同在一起。

,2 as tempid--与FATHER的temp_datetime一样,但排在FATHER后,所以TEMPID为2
,* from tm A where root=0

这样,最后总排序先按temp_datetime DESC排列后,按TEMPID、SORT排。就符合你的要求了。

我没有QQ,不好意思。
benxie 2003-08-18
  • 打赏
  • 举报
回复
学习
jianglf 2003-08-18
  • 打赏
  • 举报
回复
j9988(j9988)谢谢你,你能不能给我们讲讲原理(这是一个论坛的数据表)
j9988 2003-08-18
  • 打赏
  • 举报
回复
如果root只有0和1,且只有一级。可以这样:
--建测试表:
create table tm(id int, name varchar(10),changetime datetime,root bit,father int,content varchar(10),sort int)
insert tm select '11','aa',' 2003-08-15 12:01','1','0','12345678',' 0'
insert tm select '12','vb',' 2003-08-16 1:00','1','0','23423545',' 0'
insert tm select '13','ff',' 2003-08-15 11:00','0','11','421433124','2'
insert tm select '14','e2',' 2003-08-12 3:00','0','12','24324444','1'
insert tm select '15','33',' 2003-08-17 13:00','1','0','22234354',' 0'
insert tm select '16','21',' 2003-08-17 14:00','0','11','24231442',' 1'

语句:
select id,name,changetime,root,father,content,sort from
(
select changetime as temp_datetime,1 as tempid,* from tm where root=1
union all
select (select changetime from tm where id=A.father),2 as tempid,* from tm A where root=0
) B
order by temp_datetime desc,tempid,sort

结果:
id name changetime root father content sort
----------- ---------- ------------------------------------------------------ ---- ----------- ---------- -----------
15 33 2003-08-17 13:00:00.000 1 0 22234354 0
12 vb 2003-08-16 01:00:00.000 1 0 23423545 0
14 e2 2003-08-12 03:00:00.000 0 12 24324444 1
11 aa 2003-08-15 12:01:00.000 1 0 12345678 0
16 21 2003-08-17 14:00:00.000 0 11 24231442 1
13 ff 2003-08-15 11:00:00.000 0 11 421433124 2

(所影响的行数为 6 行)
amtyuranus 2003-08-18
  • 打赏
  • 举报
回复
用一条sql语句很难实现,不过可以通过存储过程来做

先将root=1的记录按降序放到临时表里

然后一条一条的找有没有id=father的,有就插到它后面

这里用两个循环好了,最好把没用掉的插近来

回家了,不好意思没时间写了
hjb111 2003-08-18
  • 打赏
  • 举报
回复
select * from 表a order by changetime desc
txlicenhe 2003-08-18
  • 打赏
  • 举报
回复
还真不容易看懂!

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧