[英]select distinct + group by returning more than one row
我期待以下查询
SELECT distinct t.customer_code, t.amount_spent
from table t
where t.customer_code = 'ABF7EG'
group by t.customer_code, t.amount_spent
在 PostgreSQL 中只返回一行,例如: ABF7EG 1000
但这是结果:
customer_code amount_spent
ABF7EG 934
ABF7EG 1362
ABF7EG 1820
ABF7EG 1939
ABF7EG 1953
如何解决这个问题呢?
如果我理解正确,这就是你需要做的:
SELECT distinct on(t.customer_code), t.amount_spent
from table t
where t.customer_code = 'ABF7EG'
group by t.customer_code, t.amount_spent
但在这种情况下这样做很奇怪,请提供示例数据和所需的 output
我不知道你为什么会这样。 您在GROUP BY
中有两个键,因此结果集中的每一行都有唯一的值。
我假设你想要:
select t.customer_code, sum(t.amount_spent)
from table t
where t.customer_code = 'ABF7EG'
group by t.customer_code;
也许:
select t.customer_code, array_agg(distinct t.amount_spent)
from table t
where t.customer_code = 'ABF7EG'
group by t.customer_code;
这一切都取决于你想用你的GROUP BY
计算什么。 以下示例执行sum()
和avg()
,但您需要选择最适合您的用例的aggretate function
- 您的问题不清楚。
CREATE TABLE t (customer_code TEXT, amount_spent INT);
INSERT INTO t VALUES ('ABF7EG',934),
('ABF7EG',1362),
('ABF7EG',1820),
('ABF7EG',1939),
('ABF7EG',1953);
SELECT customer_code, sum(amount_spent), avg(amount_spent)
FROM t WHERE t.customer_code = 'ABF7EG'
GROUP BY customer_code;
customer_code | sum | avg
---------------+------+-----------------------
ABF7EG | 8008 | 1601.6000000000000000
检查这个db<>fiddle
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.