【问题标题】:Selecting top 3 artist by country with respect to revenue in SQLITE 3在 SQLITE 3 中按国家/地区选择收入排名前 3 的艺术家
【发布时间】:2018-10-11 02:43:47
【问题描述】:

我有多个表格,分别是艺术家、专辑、曲目、invoice_items、invoices、customers。

我在下面写了sql查询:

select country, artistid, name, revenue from 
(select t6.country, t1.artistid, t1.name, sum(t4.quantity*t4.unitprice) as revenue 
from artists 
t1 inner join albums t2 
inner join tracks t3 
inner join invoice_items t4 
inner join invoices t5 
inner join customers t6 on t1.artistid=t2.artistid 
and t2.albumid=t3.albumid 
and t3.trackid=t4.trackid 
and t4.invoiceid=t5.invoiceid 
and t5.customerid=t6.customerid 
group by t6.country, t1.artistid 
);

查询的输出:

预期输出: 每个国家/地区按收入排序的前 3 名艺术家。因为我需要分别获得阿根廷、澳大利亚、巴西、美国的前三名。

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    使用排名函数:

    SELECT * FROM 
      (SELECT ARTISTID,
                   NAME,
                   COUNTRY,
                   REVENUE,
                   RANK () OVER (PARTITION BY COUNTRY ORDER BY REVENUE DESC) RANK
              FROM ARTISTS)
     WHERE RANK < 4
    

    https://www.sqlite.org/windowfunctions.html

    【讨论】:

      【解决方案2】:

      一个选项使用相关子查询来确定每个国家/地区的前 5 个收入来源。为方便起见,您可以将当前查询放入可重复使用的 CTE:

      WITH yourTable AS (
          SELECT t6.country, t1.artistid, t1.name, SUM(t4.quantity*t4.unitprice) AS revenue
          FROM artists t1
          INNER JOIN albums t2 ON t1.artistid = t2.artistid
          INNER JOIN tracks t3 ON t2.albumid = t3.albumid
          INNER JOIN invoice_items t4 ON t3.trackid = t4.trackid
          INNER JOIN invoices t5 ON t4.invoiceid = t5.invoiceid
          INNER JOIN customers t6 ON t5.customerid = t6.customerid
          GROUP BY t6.country, t1.artistid, t1.name
      )
      
      SELECT t1.*
      FROM yourTable t1
      WHERE artistid IN (
          SELECT t2.artistid
          FROM yourTable t2
          WHERE t1.country = t2.country
          ORDER BY t2.revenue DESC, t2.name
          LIMIT 5
      )
      ORDER BY
          country, revenue DESC;
      

      Demo

      请注意,我在LIMIT 子查询中按名称添加了订单级别。这是为了明确打破平局,如果两个或多个艺术家碰巧在给定国家有相同的收入。在这种情况下,按字母顺序较早的名称是最先显示的名称。

      【讨论】:

      • 我应该如何将第一个查询的输出存储为某个表?如果我不将其存储为表格,则此逻辑将不起作用。
      • @Nick 查看我的更新答案。您可以将查询放入 CTE。
      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多