2011-06-23 92 views
0

我想要檢索表中的所有值,按字母順序排序並將「全部」附加到頂部(全部不在表格中)。SQL排序問題

當前代碼:

SELECT 0 AS TypeID, 'All' AS [Type] 
UNION 
SELECT TypeID, [Type] FROM tbl_Type ORDER BY 2 

此訂單的一切,包括所有的,這是有問題的,因爲我在這臺所謂的「協議」,這之後的排序顯示了之前所有的值。

有沒有什麼辦法可以返回一個列表頂部的「全部」和其下的所有東西?

UPDATE:

我試圖通過Andomar和康拉德建議的解決方案,但是我得到以下錯誤:

Msg 207, Level 16, State 1, Line 4 
Invalid column name 'Type'. 
Msg 104, Level 16, State 1, Line 4 
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator. 

回答

3

你可以使用case排序'全部'前面:

SELECT 0 AS TypeID, 'All' AS [Type] 
UNION 
SELECT TypeID, [Type] FROM tbl_Type 
ORDER BY case when Type = 'All' then 1 else 2 end, Type 

編輯:根據您的評論,SQL Server不允許order by別名。使用子查詢:

SELECT * 
FROM (
     SELECT 0 AS TypeID, 'All' AS [Type] 
     UNION 
     SELECT TypeID, [Type] FROM tbl_Type 
     ) as SubQueryAlias 
ORDER BY case when Type = 'All' then 1 else 2 end, Type 

或在這種情況下,因爲類型是一個實際的表中的字段,而不是一個別名,交換聯盟的兩個部分:

SELECT TypeID, [Type] FROM tbl_Type 
UNION 
SELECT 0 AS TypeID, 'All' AS [Type] 
ORDER BY case when Type = 'All' then 1 else 2 end, Type 
+0

查看我原來帖子的更新。 – JGow

+0

@JGow:對,SQL Server惱人地不允許沒有子查詢的別名。回答編輯。 – Andomar

+0

謝謝,你編輯的第一部分工作完美! – JGow

3

隨着Andomar的答案,你也可以做到這一點來解決別名問題。

WITH CTE As 
(

    SELECT 0 AS TypeID, 'All' AS [Type] 
    UNION 
    SELECT TypeID, [Type] FROM tbl_Type 
    ORDER BY 
) 
SELECT 
    typeID, 
    Type, 
FROM 
     CTE 
ORDER BY 
    CASE 
     WHEN TypeID = 0 THEN typeID 
     ELSE Type 
    END 

但這種假設tbl_type.type的所有值都大於0

你也可以添加其他字段的CTE

WITH CTE As 
(

    SELECT 0 AS TypeID, 'All' AS [Type], 1 as sortorder 
    UNION 
    SELECT TypeID, [Type] FROM tbl_Type, 2 as sortorder 
    ORDER BY 
) 
SELECT 
    typeID, 
    Type, 
FROM 
     CTE 
ORDER BY 
    sortorder, 
    type 
+0

查看我原來的帖子的更新 – JGow

1
SELECT 0 AS TypeID, 'All' AS [Type] UNION SELECT TypeID, [Type] FROM tbl_Type ORDER BY 2 DESC 
1

你可以只添加第三列進行排序,其指示它是否是一個數據記錄(或 「全部」)

SELECT 0 AS TYPEID, '全部' AS [類型],0 AS IsDataRecord UNION SELECT TYPEID,[類型],1 AS IsDataRecord FROM tbl_Type ORDER BY 3, 2