I have a query below:
select date_trunc('day', ordertimestamp) as days
, product
, revenue
from table
The result is :
days | product | revenue
2022-07-10 | shoes | $ 430
2022-07-10 | chocolate | $ 10
2022-07-10 | shirts | $ 3.25
2022-07-10 | phones | $ 500
2022-01-02 | vests | $ 200
2022-02-03 | computers | $ 700
I need to put this table in a manner whereby the top 3 product categories by revenue for 2022-07-10 appear on ONE row like this:
2022-07-10 | phones, shoes, chocolate
as you can see they appear in descending order of revenue
I tried something like this:
SELECT
array(select products from dataset order by revenue desc limit 3) as top_three_product_categories_by_revenue
FROM table
But I’m not sure if it is accurate
3
Answers
row_number()
function to assign number to each row by a group and order .rn<3
to get only the 3 top products per date.Demo here
This code will work on DuckDB but can be easily ported to other databases. The first portion just generates fake data.
As the others already posted in the meantime:
ROW_NUMBER()
partitioned by the date column overORDER BY revenue DESC
, then filter by the resulting row number less than 4, group by the date andSTRING_AGG()
ofproduct
.