2016-01-20 99 views
-1

在選擇查詢將其放置在GROUP BY截至見下表總結現場沒有SQL

id invoice_id item_id  cost  price  quantity 
1  1   1   32.00 35.00  5 
2  2   1   32.00 35.00  6 
3  4   2   43.00 52.00  8 

所示我想組它通過它的ITEM_ID,成本,價格,而總結的數量

我已經試過這

select item_id, cost,price, sum(quantity) 
from table 
group by item_id, cost,price,quantity 

但這不會總結數量,而是單獨組它

我想拿出這個結果

item_id  cost  price  quantity 
    1   32.00 35.00  11 
    2   43.00 52.00  8 

通過從組數量將顯示此錯誤

i've tried that , this error shows, "Column 'XXXX.quantity' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 
" 
+1

刪除'group by'中的'quantity'。 –

+0

@FelixPamittan:此錯誤將顯示「列'XXXX.quantity'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 」 – marlonpd

+0

「您是否向我們顯示實際查詢?我認爲你錯誤地輸入了一些東西,或者從組中刪除數量就會很好。 – Andrea

回答

0

使用窗口SUM而不是GROUP BY

DROP TABLE IF EXISTS #temp; 

    CREATE TABLE #temp (
    id INT, 
    invoice_id INT, 
    item_id INT, 
    cost FLOAT, 
    price FLOAT, 
    quantity INT); 


    INSERT INTO #temp 
      (id 
      ,invoice_id 
      ,item_id 
      ,cost 
      ,price 
      ,quantity 
      ) 
    VALUES 
      (1,1,1,32.00,35.00,5), 
      (2,2,1,32.00,35.00,6), 
      (3,4,2,43.00,52.00,8); 


    SELECT DISTINCT 
     item_id 
     ,cost 
     ,price 
     ,SUM(quantity) OVER (PARTITION BY item_id, cost, price) Sum 
    FROM #temp 



item_id  cost     price     Sum 
----------- ---------------------- ---------------------- ----------- 
1   32      35      11 
2   43      52      8 

或者領域,如果你想包括quantity還有:

SELECT DISTINCT 
     item_id 
     ,cost 
     ,price 
     ,quantity 
     ,SUM(quantity) OVER (PARTITION BY item_id, cost, price) Sum 
    FROM #temp 
0

剛剛離開quantityGROUP BY條款:

select item_id, cost, price, sum(quantity) 
from table 
group by item_id, cost, price 
+0

我試過了,這個錯誤顯示,「列'XXXX.quantity'在選擇列表中是無效的,因爲它不包含在聚合函數或GROUP BY子句中。 」 – marlonpd

+0

呃,那是......怪異的。 SUM()是一個聚合函數。再檢查一遍。 – Andrea

+0

@marlonpd這是因爲你可以有選擇地在'SELECT'子句中包含'quantity'。 'quantity'應該只出現在'sum'聚合函數中。 –

0

group by條款 中刪除數量,因爲您還將數量分組爲

Group By子句不列入包括正在聚集