2012-08-30 80 views
1

我無法對此進行排序。我想要整個結果集由DateId然後productName排序,並且無法讓它工作。如何對聯盟進行排序全部

SELECT d.DateId, 
    s.product_name1 as productName 
FROM dbo.SaleDates d 
INNER JOIN dbo.Sale s ON s.saleId = d.saleId 

UNION ALL 

SELECT d.DateId, 
    s.product_name2 as productName 
FROM dbo.SaleDates d 
INNER JOIN dbo.Sale s ON s.saleId = d.saleId 

UNION ALL 

SELECT d.DateId, 
    s.product_name3 as productName 
FROM dbo.SaleDates d 
INNER JOIN dbo.Sale s ON s.saleId = d.saleId 
order by d.DateId, productName 

不知道基本上在哪裏以及如何添加此訂單。我不想爲每個選擇添加一個訂單,因爲那樣我會有訂單的子集。我想訂購-entire-ending結果集...

+1

你得到什麼錯誤? – gangreen

+0

你擁有的代碼應該可以工作。最後的'ORDER BY'適用於整個結果集。 (編輯:啊,只是使用'DateId'而不是'd.DateId') –

+0

是試圖馬丁,但得到ORDER BY子句在視圖,內聯函數,派生表,子查詢和公用表表達式中是無效的,除非TOP或FOR XML也被指定。當我嘗試改變視圖時。如果我突出顯示它就好,但當視圖試圖改變時,SQL運行,我明白了。 – PositiveGuy

回答

0

您可以使用CTE進行此操作。或者只是做:

Select res.DateID, res.productName from 
(
SELECT d.DateId, 
    s.product_name1 as productName 
FROM dbo.SaleDates d 
INNER JOIN dbo.Sale s ON s.saleId = d.saleId 

UNION ALL 

SELECT d.DateId, 
    s.product_name2 as productName 
FROM dbo.SaleDates d 
INNER JOIN dbo.Sale s ON s.saleId = d.saleId 

UNION ALL 

SELECT d.DateId, 
    s.product_name3 as productName 
FROM dbo.SaleDates d 
INNER JOIN dbo.Sale s ON s.saleId = d.saleId 
) 
order by res.DateId, res.productName 
2

你可以試試這個:

SELECT * FROM 
(
    SELECT d.DateId as DateId, 
     s.product_name1 as productName 
    FROM dbo.SaleDates d 
    INNER JOIN dbo.Sale s ON s.saleId = d.saleId 

    UNION ALL 

    SELECT d.DateId as DateId, 
     s.product_name2 as productName 
    FROM dbo.SaleDates d 
    INNER JOIN dbo.Sale s ON s.saleId = d.saleId 

    UNION ALL 

    SELECT d.DateId as DateId, 
     s.product_name3 as productName 
    FROM dbo.SaleDates d 
    INNER JOIN dbo.Sale s ON s.saleId = d.saleId 
) AS A 
order by DateId, ProductName 
+0

錯誤:除非還指定了TOP或FOR XML,否則ORDER BY子句在視圖,內聯函數,派生表,子查詢和公用表表達式中無效。 – PositiveGuy

+0

這是當我嘗試改變視圖我得到這個...使用你的技術 – PositiveGuy

1

引用列別名(在你的情況DateId,產品名稱)

select 1 a 
union all 
select 2 a 
order by a desc 

或引用的列數

select 1 a 
union all 
select 2 a 
order by 1 
1
Select Col1, Col2 from tblA where <some condition> 
    Union All 
    Select Col1,Col2 from tblB where <some condition> 
    Union All 
    Select Col1,Col2 from tblC where <some condition> 

    Order By 1,2 -- means by first column,second column 

-- or Order By Col1, Col2 

但你應該工作正常Order by DateId,productName

而且不是打表的銷售和SalesDate 3次,您可以通過捕捉共同作用的結果在某些臨時表設置,然後在執行聯合提高查詢性能所需的列,例如

SELECT d.DateId,s.product_name1,s.product_name2,s.product_name3 
INTO #temp 
FROM dbo.SaleDates d 
INNER JOIN dbo.Sale s ON s.saleId = d.saleId 

Select t.DateId,t.product_name1 As productName From #temp t Union All 
Select t.DateId,t.product_name2 From #temp t Union All 
Select t.DateId,t.product_name3 From #temp t 
Order By DateId,productName 

Drop Table #temp 

希望這有助於