这种复杂的orderby能不能用存储过程实现的?

zhengshaodong 2008-12-19 11:16:25
有一表tb
有几个列
id ---id
title --标题
postdate --- 发布时间
istop(bit) --- 是否置顶
topdate(datetime) ---置顶有效期 可以为null 如果为null的话则表示永久有效
现在查询后要排序的结果是
先(istop为true)且(topdate为null或topdate<DateTime.Now)的行
余下不符合上面这个条件的行按postdate排
麻烦写个这样的让我看看好吗,因为存储过程不是特别熟练,试了一两天了都没尝试出来
...全文
116 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
oraclelogan 2008-12-21
  • 打赏
  • 举报
回复
select * from tb order by case when istop = 1 and (topdate is null or topdate < getdate()) then 1 else 2 end , postdate

--id自增,换成ID
select * from tb order by case when istop = 1 and (topdate is null or topdate < getdate()) then 1 else 2 end , [ID]


aniudage 2008-12-20
  • 打赏
  • 举报
回复
学习
rockyvan 2008-12-20
  • 打赏
  • 举报
回复
Try:
ORDER BY (CASE [istop] WHEN TRUE THEN 1 ELSE 2 END),
(CASE [topdate] WHEN NULL THEN 1 ELSE 2 END),--你的“topdate <DateTime.Now”這個條件是多餘的
[postdate]
T315608 2008-12-20
  • 打赏
  • 举报
回复
学习
rucypli 2008-12-20
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 dawugui 的回复:]
SQL codeselect * from tb order by case when istop = 1 and (topdate is null or topdate < getdate()) then 1 else 2 end , postdate
[/Quote]

如果你的id是自增的,postdate换成id会快些
ChinaITOldMan 2008-12-20
  • 打赏
  • 举报
回复
learn
zhengshaodong 2008-12-20
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 rockyvan 的回复:]
Try:

SQL codeORDER BY (CASE [istop] WHEN TRUE THEN 1 ELSE 2 END),
(CASE [topdate] WHEN NULL THEN 1 ELSE 2 END),--你的“topdate <DateTime.Now”這個條件是多餘的
[postdate]
[/Quote]
我觉得topdate <DateTime.Now”這個條件并不多余
因为我想让一些新闻置顶 可以设置无限期置顶 也可以设置置顶有效期
zhengshaodong 2008-12-20
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 dawugui 的回复:]
SQL codeselect * from tb order by case when istop = 1 and (topdate is null or topdate < getdate()) then 1 else 2 end , postdate
[/Quote]
这句差点就可以了

select * from [News] order by case when istop = 1 and (topdate is null or topdate < getdate()) then 1 else 2 end , postdate desc

像有3列值一列是
id title postdate istop topdate
1 'a' 2008-1-1 true 2008-12-31
2 'b' 2008-2-1 true 2008-3-1 (这个日期已经小于DateTime.Now了)
3 'c' 2008-3-1 false null
4 'd' 2008-4-1 true null
那么我想排列顺序是 4-1-3-2
但是按照dawugui的写出来排序成了4-1-2-3了
dawugui 2008-12-19
  • 打赏
  • 举报
回复
select * from tb order by case when istop = 1 and (topdate is null or topdate < getdate()) then 1 else 2 end , postdate
liangpei2008 2008-12-19
  • 打赏
  • 举报
回复

select *
from table
order by case when XXXX then XX else XX end
zhengshaodong 2008-12-19
  • 打赏
  • 举报
回复
先(istop为true)且(topdate为null或topdate <DateTime.Now)的行
----先(istop为true)且(topdate为null或topdate <DateTime.Now)的行,符合这些条件的行也是按postdate desc排序

34,590

社区成员

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

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