使用这个:
with summed_sales_of_each_product as
(
select p.artist_name, p.product_id, sum(i.qty) as total
from product p join order_item i
on i.product_id = p.product_id
group by p.artist_name, p.product_id
),
each_artist_top_selling_product as
(
select x_in.artist_name, x_in.product_id, x_in.total
from summed_sales_of_each_product x_in where total =
(select max(x_out.total)
from summed_sales_of_each_product x_out
where x_out.artist_name = x_in.artist_name)
)
select top 3
artist_name, product_id, total
from each_artist_top_selling_product
order by total desc
但是你不能停留在这个问题上,如果一位艺术家的两种产品与最高销量并列呢?数据是这样的……
beatles yesterday 1000
beatles something 1000
elvis jailbreak rock 800
nirvana lithium 600
tomjones sexbomb 400
...使用上述查询将导致以下结果:
beatles yesterday 1000
beatles something 1000
elvis jailbreak rock 800
选择哪一个?昨天还是什么?由于您不能随意选择其中一个,因此您必须同时列出两者。另外,如果销量最高的前 10 名属于披头士乐队并且是领带乐队,每个数量为 1000 条呢?由于这是您要避免的最好的事情(即在前 3 名中报告同一艺术家),您必须修改查询,以便前 3 名报告如下所示:
beatles yesterday 1000
beatles something 1000
elvis jailbreak rock 800
nirvana lithium 600
修改:
with summed_sales_of_each_product as
(
select p.artist_name, p.product_id, sum(i.qty) as total
from product p join order_item i
on i.product_id = p.product_id
group by p.artist_name, p.product_id
),
each_artist_top_selling_product as
(
select x_in.artist_name, x_in.product_id, x_in.total
from summed_sales_of_each_product x_in
where x_in.total =
(select max(x_out.total)
from summed_sales_of_each_product x_out
where x_out.artist_name = x_in.artist_name)
),
top_3_total as
(
select distinct top 3 total
from each_artist_top_selling_product
order by total desc
)
select artist_name, product_id, total
from each_artist_top_selling_product
where total in (select total from top_3_total)
order by total desc
如果披头士乐队有另一种 900 数量的产品呢?上面的查询仍然有效吗?是的,它仍然可以工作。由于 top_3 CTE 仅关注已过滤的每位艺术家的最高数量。所以这个源数据...
beatles yesterday 1000
beatles something 1000
beatles and i love her 900
elvis jailbreak rock 800
nirvana lithium 600
tomjones sexbomb 400
...仍然会导致以下结果:
beatles yesterday 1000
beatles something 1000
elvis jailbreak rock 800
nirvana lithium 600