sql - Postgresql SELECT DISTINCT ON -
in query below i'm trying select data need distinct on columns book.title , orderdate. have tried using distinct on multiple results post below. sorry if question bit trivial. i'm in process of learning sql i'm bit of noob when comes obvious have missed.
how change query results formatted so:
month | title | quantity | total_value -----------+---------------------------------------------+----------+------------- february | internet , world wide web: how program | 15 | 899.70 march | c how program | 4 | 183.92 march | core servlets , javaserver pages | 13 | 856.70 march | internet , world wide web: how program | 21 | 1071.58
the query constructed:
select distinct on (orderdate, book.title) book.title, to_char(orderdate, 'month') "order date", orderline.quantity "order quantity", (sum(quantity*unitsellingprice)) "total value" book inner join publisher on book.publisherid=publisher.publisherid inner join orderline on book.bookid=orderline.bookid inner join shoporder on orderline.shoporderid=shoporder.shoporderid publisher.name='prentice hall' group book.title, orderdate, orderline.quantity order orderdate asc;
the results get:
title | order date | order quantity | total value ---------------------------------------------+------------+----------------+------------- internet , world wide web: how program | february | 10 | 299.90 internet , world wide web: how program | february | 5 | 149.95 c how program | march | 3 | 68.97 core servlets , javaserver pages | march | 10 | 329.50 internet , world wide web: how program | march | 20 | 519.80 c how program | march | 1 | 22.99 core servlets , javaserver pages | march | 3 | 98.85 internet , world wide web: how program | march | 1 | 15.99
thanks help!
i think you're over-complicating things here: if want total quantity each title , month, want group by title , month, , sum quantity. don't want group by quantity itself, because mean new row each distinct quantity.
that's easy in standard sql (distinct on
postgres extension, useful in few cases instead of group by
, unnecessary here):
select book.title, to_char(orderdate, 'month') "order date", sum(orderline.quantity) "order quantity", sum(quantity*unitsellingprice) "total value" [...] publisher.name='prentice hall' group book.title, to_char(orderdate, 'month') order to_char(orderdate, 'month') asc;
the rule of thumb in select
clause - , order by
clause, considered "at same level" - should either:
- listed in
group by
clause because want new row every time varies - or wrapped in aggregate function (here
sum()
) because want "roll up" according rule.
Comments
Post a Comment