1

你好我有一个像这样的查询

SELECT 4 AS sortf,XX FROM Table GROUP BY Y
UNION 
SELECT 1 AS sortf,XX FROM Table GROUP BY Y
UNION 
SELECT 2 AS sortf,XX FROM Table GROUP BY Y
UNION
SELECT 3 AS sortf,XX FROM Table GROUP BY Y
ORDER BY 3,2

我的问题是第 2 行和第 3 行没有像树一样有序。我尝试了其他一些组合,但没有奏效。 在此处输入图像描述

4

1 回答 1

0

如果您想根据数字对数据集进行排序,请将您的代码和联合放入一个公用表表达式中,然后使用 ROW_NUMBER() 函数生成行号,如下所示:

WITH CTE
AS
(
    SELECT 4 AS sortf, productid FROM Production.Products 
    UNION 
    SELECT 1 AS sortf,productid FROM Production.Products
    UNION 
    SELECT 2 AS sortf,productid FROM Production.Products
    UNION
    SELECT 3 AS sortf,productid FROM Production.Products
)
SELECT *, ROW_NUMBER() OVER (ORDER BY productid)  AS SortOrder
FROM CTE
ORDER BY SortOrder 
于 2013-07-09T09:25:49.720 回答