【发布时间】:2023-01-06 22:14:47
【问题描述】:
首先,我不确定这是否可能。
假设我有这个数据集示例
CREATE TABLE TRANSACTION(
user_id numeric,
account_id varchar,
product varchar,
colour varchar,
price numeric);
insert into transaction (user_id, account_id, product, colour, price)
values
(1, 'a1', 'biycle', 'black', 500),
(1, 'a2', 'motorbike', 'red', 1000),
(1, 'a2', 'motorbike', 'blue', 1200),
(2, 'b3', 'car', 'grey', 10000),
(2, 'b2', 'motorbike', 'black', 1250),
(3, 'c1', 'biycle', 'black', 500),
(3, 'c2', 'biycle', 'black', 525),
(3, 'c4', 'skateboard', 'white', 250),
(3, 'c5', 'scooter', 'blue', 260)
从那张桌子我们知道
真实客户总数为 3 (1,2,3) 并且
真实账户总数为 8 (a1, a2, b3, b2, c1, c2, c4, c5)
然后用这段代码
SELECT
product,
colour,
sum(price)total_price,
count(DISTINCT user_id)customer_total,
count(DISTINCT account_id)account_total
from transaction
group by
product, colour
回报是这样的
| product | colour | total_price | customer_total | account_total |
|---|---|---|---|---|
| biycle | black | 1525 | 2 | 3 |
| car | grey | 10000 | 1 | 1 |
| motorbike | black | 1250 | 1 | 1 |
| motorbike | blue | 1200 | 1 | 1 |
| motorbike | red | 1000 | 1 | 1 |
| scooter | blue | 260 | 1 | 1 |
| skateboard | white | 250 | 1 | 1 |
从上面的输出中,
如果我们合计 customer_total,它将是 8,并且
如果我们合计 account_total,它将是 9
有没有其他方法可以使 customer_total 为 3 而 account_total 为 8
【问题讨论】:
-
你能用预期的输出更新你的帖子吗?如果您没有这样的预期输出,问题就会变成基于意见的。
标签: sql postgresql group-by count