2016-01-20 56 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子句不列入包括正在聚集