时间:2016-05-03 13:30:35

标签: sql postgresql

我的表中有以下列:

name | columnA | columnB

我正在尝试调用以下查询:

SELECT name, columnA + columnB AS price
FROM house
WHERE NOT (columnA IS NULL OR columnB IS NULL)
GROUP BY name
ORDER BY price

这引起了我的注意:

house.columnA需要在GROUP BY子句中。 - 我不确定我应该怎么理解。

我想要做的是接收表格,我将name houseprice列,仅等于columnA + columnB,如果两列都不为null。我想按计算的价格对其进行排序。

我在哪里犯错?

4 个答案:

答案 0 :(得分:2)

有两种选择:

选项1 - 不需要分组。如果每个名称都有一行,则会发生这种情况,在这种情况下:

SELECT name,columnA+columnB as price
FROM house
WHERE columnA is not null 
 AND columnB is not null
ORDER BY price

选项2 - 需要分组,这意味着每个名称的行数超过1行,在这种情况下,您应该使用SUM

SELECT name,sum(columnA+columnB) as price
FROM house
WHERE columnA is not null 
 AND columnB is not null
GROUP BY name
ORDER BY price

答案 1 :(得分:0)

试试这个

SELECT name, SUM(columnA + columnB) AS price
FROM house
WHERE NOT (columnA IS NULL OR columnB IS NULL)
GROUP BY name
ORDER BY price

答案 2 :(得分:0)

我可能会误解你,但我想 你需要的是一个没有组的基本SQL查询。 sum也是一个允许您对不同行的值求和的函数。从同一行创建值的总和是trival。

这是汇总函数总和如何用于计算每条街道所有房屋的价格:

select street, sum(columnA + columnB) as price_per_street
from houses
where columnA  is not null and columnB is not null
group by street
order by price;  

这应该是你想要的:

SELECT name, columnA + columnB AS price
FROM house
WHERE columnA IS NOT NULL AND columnB IS NOT NULL
ORDER BY price

答案 3 :(得分:-1)

错误意味着您必须在GROUP BY子句中添加columnA和columnB ifstream inp(filename); while(getline(inp, line)) { //separate first word and rest of line string word= line.substr(0, line.find(" ")); string rest= line.substr(line.find(" ") + 1); DictionaryEntry de(word, rest); }