【问题标题】:Query to to get the total number of transactions each customer had per day and the number of transactions each customer had per product per day?查询以获取每个客户每天的交易总数和每个客户每天每个产品的交易数?
【发布时间】:2022-07-07 23:37:44
【问题描述】:

问题 - 编写查询以获取每位客户每天的交易总数以及每位客户每天对每种产品的交易次数。从最近到最旧的交易日期排序??

CREATE TABLE customers(
   customer_id   INTEGER  NOT NULL PRIMARY KEY 
  ,customer_name VARCHAR(15) NOT NULL
);

INSERT INTO customers(customer_id,customer_name) VALUES (1,'Thomas');
INSERT INTO customers(customer_id,customer_name) VALUES (2,'Raymond');

CREATE TABLE transactions_details(
   transaction_id   INTEGER  NOT NULL PRIMARY KEY 
  ,customer_id      INTEGER  NOT NULL
  ,product          VARCHAR(5) NOT NULL
  ,transaction_date DATE  NOT NULL
);

INSERT INTO transactions_details(transaction_id,customer_id,product,transaction_date) VALUES (1,1,'Milk','2022-08-02');
INSERT INTO transactions_details(transaction_id,customer_id,product,transaction_date) VALUES (2,2,'Milk','2022-08-03');
INSERT INTO transactions_details(transaction_id,customer_id,product,transaction_date) VALUES (3,2,'Eggs','2022-08-03');
INSERT INTO transactions_details(transaction_id,customer_id,product,transaction_date) VALUES (4,1,'Milk','2022-08-02');
INSERT INTO transactions_details(transaction_id,customer_id,product,transaction_date) VALUES (5,1,'Bacon','2022-08-03');
INSERT INTO transactions_details(transaction_id,customer_id,product,transaction_date) VALUES (6,1,'Milk','2022-08-02');

【问题讨论】:

  • 你尝试了什么?这似乎是一个标准的 join+groupby
  • 我是初学者!只是尝试我的手。如果您能提供帮助,不胜感激……谢谢!
  • 你尝试了什么?

标签: mysql sql mysql-workbench


【解决方案1】:

在 MySQL 8+ 上,您可以使用 COUNT(*) OVER(partition by)。按部分划分定义了每天的总数和每天的总产品。

试试:

with cte as (
              select customer_name,
                     transaction_date,
                     product,
                     count(*) over (partition by customer_name,transaction_date ) as tot_per_day,
                     count(*) over (partition by customer_name,transaction_date,product ) as product_per_day
              from customers c
              inner join transactions_details td on c.customer_id=td.customer_id 
) select cte.* 
  from cte
  order by transaction_date desc;  

https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=04d6ef506dc0fe6ade23c288f0a6c797

【讨论】:

    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2020-05-24
    • 2021-09-29
    • 2018-12-24
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多