SQL Query,Union Order by like tree

时间:2013-07-09 09:13:52

标签: sql sql-server sql-order-by union

您好我有一个像

这样的查询
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行没有按树排序。我尝试了一些其他组合,但它没有用。 enter image description here

1 个答案:

答案 0 :(得分: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