求一SQL语句

zlydaaa 2003-09-20 12:03:24
刚才在这儿看到这么一个问题

px表中有两个字段 id 和 datetime, 如果datetime内时间是3天内的则排序在最前,并按id号排序,3天后的按id 排序。

回答是
Select * from px
order by (case when datediff(d,datatime,getdate())<=3 then 1 else 2 end),id

但现在
如果datetime内时间是3天内的则排序在最前,并按datetime排序,3天后的按照ID排序.
该怎么写?

...全文
28 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2003-09-20
  • 打赏
  • 举报
回复
Select * from px where datediff(d,datetime,getdate()) <= 3 order by datetime
Union all
Select * from px where datediff(d,datetime,getdate()) > 3 order by id
txlicenhe 2003-09-20
  • 打赏
  • 举报
回复
Try:
Select * from px where datediff(d,datetime,getdate()) <= 3 order by datetime
Union all
Select * from px where datediff(d,datetime,getdate()) > 3 order by id
zjcxc 元老 2003-09-20
  • 打赏
  • 举报
回复
上面的是我测试的语句,按照你的表应该是:

select * from px
order by case when datediff(day,[datetime],getdate())<=3 then datediff(day,[datetime],getdate()) else id+3 end
zjcxc 元老 2003-09-20
  • 打赏
  • 举报
回复
如果你的日期排序仅按日期大小,不考虑时间的话,可以用下面的方法:

select * from px
order by case when datediff(day,[datetime],getdate())<=3 then datediff(day,[datetime],getdate()) else myid+3 end
CCEO 2003-09-20
  • 打赏
  • 举报
回复
Select * from px
order by
case when datediff(d,[datatime],getdate())<=3 then [datatime]
else '9999-12-31 23:59:59'
end,
CASE WHEN datediff(d,[datatime],getdate())<=3 then -2147483648
ELSE ID
END


呵呵

txlicenhe 2003-09-20
  • 打赏
  • 举报
回复
用这个一定行了。
Select id,[datetime] from
(
Select *,(select sum(1) from px where [datetime] <= a.[datetime]) as iid1,1 as iid2 from px a where datediff(day,datetime,getdate()) <= 3
Union all
Select *,id as iid1,2 as iid2 from px where datediff(day,datetime,getdate()) > 3
) temp
order by iid2,iid1
Robin 2003-09-20
  • 打赏
  • 举报
回复
不对,确切的说,用view就可以了!
Robin 2003-09-20
  • 打赏
  • 举报
回复
用临时表,的了!
txlicenhe 2003-09-20
  • 打赏
  • 举报
回复
Sorry: Union all 不支持前后语句用order by
try:
Select id,[datetime] from
(
Select *,(select sum(1) from px where [datetime] <= a.[datetime]) as iid1,1 as iid2 from px a where datediff(day,datetime,getdate()) <= 3
Union all
Select *,id as iid1,2 as iid2 from px where datediff(day,datetime,getdate()) > 3
) temp
order by iid2,iid1

lyyrw 2003-09-20
  • 打赏
  • 举报
回复
SELECT IDENTITY(int, 1,1) as id0, Recode_ID, [Date] into #temp
FROM FA_VIEW_10100000
where datediff(d,date,getdate())<=90 order by date desc
go
insert into #temp
select Recode_ID, [Date]
FROM FA_VIEW_10100000
where datediff(d,date,getdate())>90 order by recode_id
go
select recode_id,date from #temp order by id0
drop table #temp
go
lyyrw 2003-09-20
  • 打赏
  • 举报
回复
使用临时表
leimin 2003-09-20
  • 打赏
  • 举报
回复
Select * from px where datediff(d,datetime,getdate()) <= 3 order by datetime
Union all
Select * from px where datediff(d,datetime,getdate()) > 3 order by id

34,874

社区成员

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

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