2012-07-25 442 views
0

我有兩個表,我想編寫一個查詢,將給予我這樣做的最高和最低值,但它的顯示''一些錯誤附近工會'... (使用union就是這樣)在SQL如何找到最低和最高值

select TOP 1 od.productid,od.unitprice,totalprice=(od.unitprice-od.discount) from orderdetails od 
inner join 
orders o 
on od.orderid=o.orderid 
where o.orderdate between '10/7/1997' and '10/14/1997' 
order by totalprice asc 

union 

select TOP 1 od.productid,od.unitprice,totalprice=(od.unitprice-od.discount) from orderdetails od 
inner join 
orders o 
on od.orderid=o.orderid 
where o.orderdate between '10/7/1997' and '10/14/1997' 
order by totalprice asc 

我在做什麼錯?

+2

[**你嘗試過什麼?**](http://whathaveyoutried.com) – 2012-07-25 05:27:19

回答

1

讓我們假設您使用的是Sql Server。

您不能將ORDER BY作爲聯合首選部分的一部分。

如果您想使用order by,您需要使用sub選項。

喜歡的東西

DECLARe @TABLE TABLE(
     Val VARCHAR(20) 
) 

SELECT * 
FROM (
      SELECT TOP 1 
        Val 
      FROM @TABLE 
      ORDER BY val 
     ) minVal 
UNION 
SELECT * 
FROM (
      SELECT TOP 1 
        Val 
      FROM @TABLE 
      ORDER BY val DESC 
     ) maxVal 
+0

非常感謝u必須解決我的概率的解決方案是 SELECT * FROM(選擇TOP 1 od.productid,od.unitprice,totalprice =(od.unitprice-od.discount)from orderdetails od inner join orders o on od.orderid = o.orderid where o.orderdate between '10/7/1997'和'10/14/1997' order by totalprice asc )MAXVALUE UNION SELECT * FROM ( 選擇TOP 1 od.productid,od.unitprice,totalprice =(od.unitprice-od.discount)從ORDERDETAILS OD 內部聯接 級O 上od.orderid = O .orderid 其中'10/7/1997'和'10/14/1997'之間的訂單數量爲 order by totalprice desc )minvalue – ashi 2012-07-25 05:40:14

相關問題