我无法对此进行排序。我希望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-结束结果集......
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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次,而不是单击Sales和SalesDate表,例如。
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
希望这有帮助
答案 3 :(得分: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