0

假设我有一张包含商家信息的表格。

我希望我的结果集按此顺序显示,但有一个查询:

第一:按 created_date 的顺序显示最近创建的 5 个列表。然后:显示其余的,但以随机顺序显示。

我的领域:

[BusinessName]
[Date_Created]

因此,如果表中有 100 个企业,我希望列表显示最近创建的 5 个,然后以随机顺序显示其余的。

预先感谢您的帮助!

4

1 回答 1

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 -CASEORDER 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()
于 2013-05-27T00:06:21.647 回答