Using LATERAL JOIN To Get Top N per Group

kata programming

مساله:

یک schema در ادامه به شما معرفی می شود، که با استفاده از LATERAL join باید ۲ نمایش آخر برای تمام دسته بندی ها را نمایش دهید.

اولویت نتیجه باید به صورت زیر باشد:

  • نام دسته بندی
  • تعداد نمایش پست از بزرگ به کوچک
  • شناسه پست از کم به زیاد

نکته:

بعضی از دسته بندی ها بیشتر از ۲ تا یا هیچ پستی ندارن.

دو یا چند پست درون دسته را می توان با تعداد بازدیدها یکسان کرد.

Schema

categories

posts

خروجی باید به صورت زیر باشد:


Description

Given the schema presented below write a query, which uses a LATERAL join, that returns two most viewed posts for every category.

Order the result set by:

-category name alphabetically

-number of post views largest to lowest

-post id lowest to largest

Note:

-Some categories may have less than two or no posts at all.

-Two or more posts within the category can be tied by (have the same) the number of views. Use post id as a tie breaker – a post with a lower id gets a higher rank.

Schema

categories

posts

Desired Output

The desired output should look like this:

category_id – category id

category – category name

title – post title

views – the number of post views

post_id – post id


راه حل ها:

SELECT c.id category_id, c.category, p.title, p.views, p.id post_id
FROM categories c
LEFT JOIN LATERAL( 
    SELECT title, views, id
    FROM posts
    WHERE category_id = c.id
    ORDER BY views DESC
    LIMIT 2) p ON true
ORDER BY 2, 4 DESC, 5;
SELECT c.id category_id, category, title, views, p.id as post_id
FROM categories c
LEFT JOIN LATERAL (
  SELECT * FROM posts p
  WHERE p.category_id = c.id
  ORDER BY views DESC, p.id
  LIMIT 2
) p on true
ORDER BY category, views DESC, post_id
select 
  c.id as category_id,
  c.category,
  ps.title,
  ps.views,
  ps.post_id  
from categories c
left join lateral (
  select 
    p.category_id,
    p.title,
    p.views,
    p.id as post_id
  from posts p
  where p.category_id = c.id
  order by views desc
  limit 2
) ps on ps.category_id = c.id
order by c.category, ps.views desc, ps.post_id;

دیدگاهتان را بنویسید