0

I have two tables named Purchase and PurchaseOrder and each of the tables have the following fields:

Purchase
---------
id
date_shipped
id_po          -> FK of Purchase Order

PurchaseOrder
---------
id
date_po

I need to group them based on PurchaseOrder's date_po year. So far, I've been using the date_shipped field of the Purchase table with the following query:

select extract(year from date_shipped), count(*) from purchase
    group by(extract(year from date_shipped));

Now, I need to join the two tables and group them by the year of PurchaseOrder's date_po instead of Purchase's date_shipped field. I've tried various queries but can't quite achieve the results. One of the queries I tried is:

select extract(year from po.date_shipped), count(*) from purchase p 
    inner join purchase_order po on p.id_po = po.id
    group by(extract(year from po.date_po));

Any help would be appreciated!

8
  • Please be more specific how it doesn't work, because the query as shown will result in an error because your purchase_order table has no column date_shipped. And the resulting obvious error message should be included in the question, and if that isn't the actual problem, then you need to revise your question to include the actual query and explain why it doesn't work (include sample data, expected result and actual result and why you think that is wrong). Commented Mar 7, 2018 at 18:05
  • @MarkRotteveel yep, that was supposed to be date_po and not date_shipped. Updated the question. Commented Mar 7, 2018 at 18:08
  • Try ( select Year(po.date_po), count(*) from purchase p inner join purchase_order po on p.id_po = po.id group by Year(po.date_po); ) Commented Mar 7, 2018 at 18:09
  • 1
    See the second part of my comment, you need to explain how the query doesn't work. Commented Mar 7, 2018 at 18:09
  • @RajneeshVaishwar PostgreSQL has no function YEAR, extract(year from <timestamp/date>) is the correct function (which is defined in the SQL standard) Commented Mar 7, 2018 at 18:12

1 Answer 1

1

If you have a group by clause you can only use terms from there (or row-function applied to them) and aggregate terms in the select list:

SELECT     EXTRACT(YEAR FROM po.date_po), COUNT(*)
FROM       purchase p 
INNER JOIN purchase_order po ON p.id_po = po.id
GROUP BY   EXTRACT(YEAR FROM po.date_po)
Sign up to request clarification or add additional context in comments.

1 Comment

I had been using the wrong column, it was supposed to be id_purchase_order and not id_po. Thank's a lot for your time. Accepting answer to stop wasting anyone else's time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.