2014-04-02 80 views
2

我有一個選擇語句顯示公司列表。SQL添加所有選擇語句

SELECT distinct [Company] 
    FROM [Records] 

如何添加條目「ALL」作爲返回列表中的第一項?

+0

見'UNION'。但是,技術上,您必須爲整個結果集訂購保證結果。 Ref http://blog.sqlauthority.com/2012/10/30/sql-server-union-all-and-order-by-how-to-order-table-separately-while-using-union-all/ – user2864740

回答

2

使用union allorder by

select company 
from ((select distinct company, 1 as ordering from records) 
     union all 
     (select 'ALL', 0) 
    ) t 
order by ordering; 

在實踐中,以下似乎工作:

select 'ALL' as company 
union all 
select distinct company from records; 

但是,SQL Server不保證這些按順序執行。在實踐中,我從來沒有發現這種說法不會把ALL放在第一位,但據我所知,並不能保證。

0

嘗試與UNION ALL

SELECT 'ALL' 
    UNION ALL 
    SELECT distinct [Company] 
     FROM [Records] 
0
SELECT 'ALL' 
UNION ALL 
SELECT distinct [Company] 
FROM [Records] 
1

您可以使用UNION ALL並添加順序爲:

SELECT [Company] FROM 
    (SELECT 'All' as [Company], 0 as RecordOrder 
    UNION ALL 
    SELECT distinct [Company], 1 as RecordOrder 
    FROM [Records]) X 
ORDER BY RecordOrder