我有带有movieID,movieName和movieDate的电影表。 我想首先选择过去24小时内添加的所有电影,并按日期订购,其余订单按newid()排序。
即
1 babylon 28/09/2010 16:00
2.12 monekys 28/09/2010 8:00
3.se7en 25/09/2010 5:00
4.snatch 26/09/2010 18:00
我怎样才能实现它?
最终答案是所有其他答案的组合,这些答案都做得很好......
declare @date smalldatetime
set @date = dateadd(dd,-2,getdate())
DECLARE @d AS int
SET @d = DATEPART(ss, GETDATE()) + 3
select
movieID,
movieTitle,
movieDate
from Movies
order by
case
when movieDate>@date
then movieDate end desc, movieID % @d
答案 0 :(得分:2)
另一个要测试的人。
ORDER BY
CASE WHEN movieDate >= DATEADD(hour, -24, GETDATE()) THEN movieDate END DESC,
CHECKSUM(NEWID())
答案 1 :(得分:1)
尝试类似(未经测试)的内容:
SELECT
*
FROM (
SELECT -- start with the newest movies
movieID,
movieName,
movieDate,
1 AS rnk -- new will need it to sort them property
FROM
movies
WHERE
movieDate >= DATEADD(h, -24, GETDATE()) -- from last 24 hours
UNION ALL -- there will be no duplicates (so, so)
SELECT
movieID,
movieName,
movieDate,
2 AS rnk -- goes after the newest ones
FROM
movies
WHERE
movieDate < DATEADD(hh, -24, GETDATE()) -- older then 24 hours
) AS movies
ORDER BY
rnk,
CASE WHEN rnk = 1 THEN movieDate ELSE newid() END -- order by movieDate newest movies and by newid() older ones
您确定要显示所有超过24小时的电影吗?
movieID
列上模数的可能技巧会更快,然后使用newid()
函数进行排序。
而不是像newid()
这样的东西:
DECLARE @d AS int
SET @d = DATEPART(ss, GETDATE()) + 3 -- to avoid division by 0
然后在ORDER
子句而不是newid()
使用movieID % @d
。
答案 2 :(得分:1)
这样的事情:
ORDER BY
CASE
WHEN [movieDate] BETWEEN DATEADD(d, -1, GETDATE()) AND GETDATE()
THEN [movieDate]
ELSE [movieID]
END DESC
答案 3 :(得分:1)
尝试
DECLARE @date AS datetime
SET @date = DateAdd(hh, -25, GetDate())
SELECT
*
FROM (
SELECT
movieID,
movieName,
movieData,
movieDate AS dateToOrder
FROM
movies
WHERE
movieDate >= DateAdd(h, -24, GetDate())
UNION ALL
SELECT
movieID,
movieName,
movieData,
@date AS dateToOrder
FROM
movies
WHERE
movieDate < DateAdd(hh, -24, GetDate()) -- older then 24 hours
) AS movies
ORDER BY dateToOrder DESC, movieID