2017-08-03 67 views
1

什麼是錯的這個SQL語句,我不斷收到此錯誤:ORA-00979:不是GROUP BY表達式ORDERDETAILS

SQL錯誤:ORA-00979:不是GROUP BY表達式 00979. 00000 - 「不是一個GROUP BY表達式」 *原因:
*操作:

SELECT orderdetails.orderid, 
    orderdate, 
    sum (quantity *(unitprice - unitprice * discount))as "Order Total" 
FROM orderdetails 
    INNER JOIN orders orders on orderdetails.orderid = orders.orderid 
WHERE customerid = 'ERNSH' 
GROUP BY orderdetails.orderid 
ORDER BY "Order Total" desc; 

如果我有像發貨另一個變量?

SELECT orderdetails.orderid, orderdate, NVL2(Shippeddate, "Not Shipped" , "Shipped") as "Shipped" ,sum (quantity *(unitprice - unitprice * discount))as "Order Total" FROM orderdetails 
INNER JOIN orders orders on orderdetails.orderid = orders.orderid 
WHERE customerid = 'ERNSH' 
GROUP BY orderdetails.orderid , orderdate, Shipped 
ORDER BY "Order Total" desc; 
+3

將訂單日期添加到GROUP BY子句---'order by orderdetails.orderid,orderdate' – GurV

+1

任何原因您將餐單'orders'別名爲'orders'?唯一可能的用途是,您可以通過名稱'orders'而不是名稱'orders'來引用它。我沒有看到... – mathguy

回答

2

要麼增加訂購日期到GROUP BY子句:

select orderdetails.orderid, 
    orderdate, 
    sum(quantity * (unitprice - unitprice * discount)) as "Order Total" 
from orderdetails 
inner join orders orders on orderdetails.orderid = orders.orderid 
where customerid = 'ERNSH' 
group by orderdetails.orderid, orderdate 
order by "Order Total" desc; 

或在列中使用聚合函數,如果它不應該被子句是組:

select orderdetails.orderid, 
    max(orderdate) as orderdate, --- see which function is suitable 
    sum(quantity * (unitprice - unitprice * discount)) as "Order Total" 
from orderdetails 
inner join orders orders on orderdetails.orderid = orders.orderid 
where customerid = 'ERNSH' 
group by orderdetails.orderid 
order by "Order Total" desc; 

以上兩句在語法上是正確的,但邏輯上你必須做出決定。

此外,儘可能使用較小的別名來乾淨地編寫查詢,並始終使用別名/表名限定列名。

+0

我們必須包含訂單日期的原因是什麼,但是我們不必在group by子句中包含「訂單總額」?類似group by orderdetails.orderid,orderdate,「訂單總計」 – user2371290

+0

「GROUP BY」子句必須具有「SELECT」子句中存在的所有非聚合列/表達式。 「訂單總額」是彙總的結果。所以,不在團隊中。這正是我爲什麼不需要在第二個查詢中的group by子句中包含orderdate的原因 - 因爲我們在該列上使用了聚合函數。 – GurV

+0

如果我有另一個變量如發貨? SELECT order orderdetails.orderid,orderdate,NVL2(Shippeddate,「Not shipped」,「Shipped」)as「Shipped」,sum(quantity *(unitprice - unitprice * discount))as「Order Total」FROM orderdetails INNER JOIN orders orderdetails.orderid = orders.orderid WHERE customerid ='ERNSH' GROUP BY orderdetails.orderid,orderdate,Shipped ORDER BY「Order Total」desc; – user2371290

相關問題