我有这样的查询:
SELECT
table1.*,
sum(table2.amount) as totalamount
FROM table1
join table2 on table1.key = table2.key
GROUP BY table1.*;
我收到错误:列“table1.key”必须出现在GROUP BY子句中或用于聚合函数。
有没有办法将“所有”字段分组?
答案 0 :(得分:4)
没有用于按所有列进行分组的快捷语法,但在所描述的情况下可能没有必要。 如果 +------+-------+-------+
| ID | Name | Pass |
+------+-------+-------+-+
| 1165 | Exc |Itm|Pr|St|
| | +---------+
+------+-------| Sc|20|1 |
+---------+
列是主键,则在您使用它时就足够了:
key
答案 1 :(得分:0)
您必须在group by
中指定所选的所有列名称,这些列名称不属于聚合函数(SUM/COUNT
等)
select c1,c2,c4,sum(c3) FROM totalamount
group by c1,c2,c4;
避免在group by
中再次写入列的快捷方式是将它们指定为数字。
select c1,c2,c4,sum(c3) FROM t
group by 1,2,3;
答案 2 :(得分:0)
我找到了另一种解决方法,但并不完美,但可能很有用:
SELECT string_agg(column_name::character varying, ',') as columns
FROM information_schema.columns
WHERE table_schema = 'your_schema'
AND table_name = 'your_table
然后将此选择结果应用于主查询,如下所示:
$columns = $result[0]["columns"];
SELECT
table1.*,
sum(table2.amount) as totalamount
FROM table1
join table2 on table1.key = table2.key
GROUP BY $columns;