假设我有一张包含商家信息的表格。
我希望我的结果集按此顺序显示,但只有一个查询:
首先:按created_date的顺序显示最近创建的5个列表。 然后:以随机顺序显示其余部分。
我的领域:
[BusinessName]
[Date_Created]
因此,如果我在表中有100个商家,我希望列表显示最近创建的5个商家,然后以随机顺序显示其余商品。
提前感谢您的帮助!
答案 0 :(得分:2)
选项A - 将前5名和其他子查询分成两个子查询,并使用UNION
WITH CTE_TOP5 AS
(
SELECT TOP 5 BusinessName, Date_Created, ROW_NUMBER() OVER (ORDER BY DATE_CREATED DESC) RN FROM dbo.YourTable
ORDER BY Date_Created DESC
)
, CTE_REST AS
(
SELECT BusinessName, Date_Created FROM dbo.YourTable
EXCEPT
SELECT BusinessName, Date_Created FROM CTE_TOP5
)
,CTE_RESTRANDOM AS
(
SELECT BusinessName, Date_Created, ROW_NUMBER() OVER (ORDER BY NEWID()) + 5 RN FROM CTE_REST
)
SELECT * FROM CTE_TOP5
UNION ALL
SELECT * FROM CTE_RESTRANDOM
ORDER BY RN
选项B - CASE
ORDER BY
;WITH CTE_TOP5 AS
(
SELECT TOP 5 *, ROW_NUMBER() OVER (ORDER BY DATE_CREATED DESC) RN FROM dbo.YourTable
ORDER BY Date_Created DESC
)
SELECT yt.*
FROM dbo.YourTable yt
LEFT JOIN CTE_TOP5 t5 ON yt.BusinessName = t5.BusinessName
AND yt.Date_Created = t5.Date_Created
ORDER BY CASE WHEN t5.RN IS NOT NULL THEN t5.RN ELSE 6 END, NEWID()
选项C - 类似于B,但没有CTE,ROW_NUMBERS和JOINS - 整个逻辑进入ORDER BY
SELECT *
FROM dbo.YourTable yt
ORDER BY CASE WHEN yt.Date_Created IN (SELECT TOP 5 yt2.Date_Created
FROM dbo.YourTable yt2
ORDER BY yt2.Date_Created DESC)
THEN yt.Date_Created
ELSE '1900-01-01'
END DESC, NEWID()