ORDER BY子句中的SQL Server自定义排序

时间:2016-06-15 06:36:48

标签: sql sql-server stored-procedures

ALTER PROCEDURE sp_1
AS
BEGIN
    SELECT B.ID, 'B' AS Name
    FROM tableB inner join table a inner join table c
    UNION
    SELECT A.ID, 'A' AS NAME
    FROM tableA inner join table b inner join table c
    UNION
    SELECT C.ID, 'C' AS NAME
    FROM tableC inner join table a inner join table b
    ORDER BY CASE WHEN Name = 'A' THEN '1'
          ELSE Name END ASC
END

上面的代码返回无效的列名'Name'。无论如何,我可以通过使用订单来定制'名称,而无需任何新的参数。

4 个答案:

答案 0 :(得分:0)

您必须按顺序使用别名,因为您必须使用具体列,但您可以使用公用表表达式轻松实现此目的,例如

WITH MY_CTE (col1, col2, col3)
AS
-- Define the CTE query.
(
    SELECT col1, prop2 as col2, col3
    FROM table
)
-- Define the outer query referencing the CTE name.
SELECT col1, col2, col3
FROM MY_CTE
ORDER BY col2
GO

这只是指向方向

的一个例子

答案 1 :(得分:0)

可以通过子查询实现这一点,而无需任何新的变量/参数

ALTER PROCEDURE sp_1
AS
BEGIN
    SELECT SQ.ID, SQ.Name FROM (
        SELECT B.ID, 'B' AS Name
        FROM table B inner join table a inner join table c
        UNION
        SELECT A.ID, 'A' AS NAME
        FROM table A inner join table b inner join table c
        UNION
        SELECT C.ID, 'C' AS NAME
        FROM table C inner join table a inner join table b
    ) SQ
    ORDER BY CASE WHEN SQ.Name = 'A' THEN '1'
          ELSE SQ.Name END ASC
END

答案 2 :(得分:0)

SELECT B.ID, 'B' AS Name, 1 as ExplicitOrderGroup
FROM tableB inner join table a inner join table c
UNION
SELECT A.ID, 'A' AS NAME, 0 as ExplicitOrderGroup
FROM tableA inner join table b inner join table c
UNION
SELECT C.ID, 'C' AS NAME, 1 as ExplicitOrderGroup
FROM tableC inner join table a inner join table b
ORDER BY ExplicitOrderGroup, Name

注意,UNION(其行为有点像DISTINCT)现在不会折叠具有不同ExplicitOrderGroup的相同行。你必须确定它是否正常,或者你还需要其他一些行为。

答案 3 :(得分:0)

在这种情况下,我会为优先级添加一个额外的列。 像这样:

ALTER PROCEDURE sp_1
AS
BEGIN
    SELECT B.ID, 'B' AS Name, 2 AS prio
    FROM tableB inner join table a inner join table c
    UNION
    SELECT A.ID, 'A' AS NAME, 1 AS prio
    FROM tableA inner join table b inner join table c
    UNION
    SELECT C.ID, 'C' AS NAME, 2 AS prio
    FROM tableC inner join table a inner join table b
    ORDER BY prio ASC, Name ASC
END