【问题标题】:count real total customer by product groupby按产品组计算真实客户总数
【发布时间】: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


【解决方案1】:

您可以按以下方式计算帐户和客户总数;

SELECT
    product,
    colour,
    sum(price)total_price,
    (select count(DISTINCT  user_id) from transaction) as customer_total,
    (select count(DISTINCT account_id) from transaction) as account_total
 from transaction
 group by 
    product, colour

【讨论】:

    猜你喜欢
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多