【问题标题】:Use 1 SQL query to join 3 tables and find the category of products that generates the most revenue for each customer segment使用 1 个 SQL 查询连接 3 个表,并找到为每个客户群产生最多收入的产品类别
【发布时间】:2021-07-14 22:57:46
【问题描述】:

我正在使用 SQLite3 进行以下查询。

我有一个名为“产品”的表,如下所示:

我有一个名为“事务”的表,如下所示:

我有一个名为“segments”的表格,如下所示:

对于每个活跃的细分,我想找到产生最高收入的类别。

我认为我知道如何在 3 个不同的查询中做到这一点。

create table table1 as
SELECT s.seg_name, p.category, t.item_qty * t.item_price as revenue
from segments s
JOIN
transactions t
on s.cust_id = t.cust_id
JOIN products p
on p.prod_id = t.prod_id
where s.active_flag = 'Y'
order by s.seg_name, p.category
;

create table table2 as
select seg_name, category, sum(revenue) as revenue
from table1
group by seg_name, category;

select seg_name, category, max(revenue) as revenue
from table2
group by seg_name;

如何在 1 个查询中做到这一点

【问题讨论】:

    标签: sql sqlite group-by max sql-order-by


    【解决方案1】:

    这是一种方法:

    select seg_name,category,revenue
    from 
    (
    SELECT
        s.seg_name,
        p.category,
        sum(t.item_qty * t.item_price) as revenue,
        rank() over (partition by seg_name order by sum(t.item_qty * t.item_price) desc) rn 
    from
        segments s
        JOIN transactions t on s.cust_id = t.cust_id
        JOIN products p on p.prod_id = t.prod_id
    where
        s.active_flag = 'Y'
    group by seg_name, p.category
    ) t
    where rn = 1
    

    【讨论】:

    • 这行得通!但是,如何在最终输出中省略排名列(rn)的显示?
    • @Iterator516 是的,别名错误,还用您用于记录的 dbms 标记您的问题
    • 抱歉 - 我不知道我使用的是什么 DBMS。有人只是将 .db 文件发送给我。我将它上传到sqliteonline.com,并使用该接口运行 SQL。
    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多