1

I have the following orders table in a postgres 9.6 db:

orders 
item_id, created_at (a timestamp ie Rails app)

I'd like to get back a list of item_ids and distinct years and a count like this:

item_id year count
------- ---- -----
23 2017 23
24 2017 45 
24 2018 11 

How would I do this? I tried something like this but am stuck:

select item_id, extract(year from created_at) from orders where group by item_id, created_at;
Husam Mohamed
4321 gold badge4 silver badges16 bronze badges
asked Mar 22, 2018 at 3:56

1 Answer 1

2

You were nearly there, but you need to group by the year, not the timestamp value:

select item_id, extract(year from created_at), count(*)
from orders 
where ....
group by item_id, extract(year from created_at);
answered Mar 22, 2018 at 8:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.