နားလည်ထားရမယ့် အချက်
Aggregate function က row အများကို summary value အဖြစ်ချုံ့ပြီး `GROUP BY` က group တစ်ခုစီအတွက် summary ထုတ်ပါတယ်။ `WHERE` က grouping မတိုင်မီ filter လုပ်ပြီး `HAVING` က group ပြီးမှ filter လုပ်ပါတယ်။ Window function က row မချုံ့ဘဲ group context ထဲက rank၊ running total စတာတွက်ပေးပါတယ်။
လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်
Tutorial တစ်ခုစီ၏ lesson count နဲ့ total duration ကိုတွက်ပြီး catalog အတွင်း duration rank ထည့်မယ်။ Join multiplication အန္တရာယ်ရှိရင် child table ကိုအရင် aggregate လုပ်ပြီးမှ တခြား relation နဲ့ join ပါ။
အတူတူ စမ်းရေးကြည့်မယ်
WITH totals AS (
SELECT t.tutorial_id, t.title,
count(l.lesson_id) AS lesson_count,
coalesce(sum(l.duration_minutes), 0) AS total_minutes
FROM app.tutorials t
LEFT JOIN app.lessons l USING (tutorial_id)
GROUP BY t.tutorial_id, t.title
)
SELECT *, dense_rank() OVER (ORDER BY total_minutes DESC) AS duration_rank
FROM totals
ORDER BY duration_rank, title;Tutorial summary rows နှင့် duration rank ကိုရမည်။၅ မိနစ် စမ်းကြည့်
User တစ်ယောက်စီ enrollment count ကိုတွက်ပြီး ၃ ခုနှင့်အထက်ရှိသူသာ HAVING ဖြင့်ရွေးပါ။
သတိလေးတစ်ချက်
Group မလုပ်ထားသော column ကို SELECT ထဲတန်းထည့်လို့မရပါ။ Value တစ်ခုတည်းဖြစ်ကြောင်း key dependency သို့ aggregate ဖြင့်ရှင်းရပါတယ်။
PostgreSQL — Aggregate Functions — PostgreSQL Global Development Group