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

基本上不知道在哪里以及如何添加这个订单。我不想为每个选择添加一个 order by,因为那样我就会有排序的子集。我想订购-整个-结束的结果集...

4

4 回答 4

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
于 2012-08-30T06:36:01.413 回答
1

参考列别名(在您的情况下为 DateId、Productname)

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

或参考列号

select 1 a
union all
select 2 a
order by 1
于 2012-08-30T07:25:27.180 回答
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

此外,您可以通过在某个临时表中捕获公共结果集然后在所需列上执行联合来提高查询的性能,而不是点击表 Sales 和 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

希望这可以帮助

于 2012-08-30T07:43:52.150 回答
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
于 2012-08-30T06:35:26.287 回答