使用add将新列添加到现有表

时间:2014-05-13 11:16:48

标签: sql postgresql

下面给出的是我想要根据productid

计算的表格
  +-----------+-----------+----------+
 'productid   |     free  |  qty     |
 '------------+-----------+----------+
 '     2372   |      0    |    100   |
 '------------+-----------+----------+
 '     2311   |      0    |    100   |
 '------------+-----------+----------+
 '     2311   |      1    |     10   |
 '------------------------------------

我需要得到以下结果

  +----------- +-----------+
 'productid   |     toqty  |  
 '------------+-----------+
 '     2372   |     100    |    
 '------------+-----------+
 '     2311   |     110    |     
 '-------------------------+
我试过的是。

select sum(qty) as totQty 
from tmpprch 
where productid=(select productid from tmpprch) 

并坚持到这里(ERROR: more than one row returned by a subquery used as an expression

database : PostgreSQL

2 个答案:

答案 0 :(得分:3)

如果我理解正确,那么您的查询过于复杂。这是一个简单的聚合:

select productid, sum(qty) as totQty
from tmpprch
group by productid;

您从哪里获得了查询形式的想法?

答案 1 :(得分:0)

您需要使用分组依据子句。 以下是一些重要的链接http://www.w3schools.com/sql/sql_groupby.asp

http://technet.microsoft.com/en-us/library/ms177673.aspx

这是简单的查询

SELECT productid, SUM(qty) AS totQty
FROM tmpprch
Group By productid;
相关问题