skip to Main Content

I’m just learning SQL, using Postgres. I have fruit sales data, how can I retrieve fruit that is only sold from the certain date to another date. I use a query like this but error

SELECT product_name,
       min (purchase_date) AS purchase_date
FROM sales
where purchase_date not in (purchase_date <= '2021-01-01' and purchase_date >= '2021-01-10')
GROUP BY product_name
ORDER by product_name asc ;

2

Answers


  1. It is BETWEEN you’re looking for, I presume.

    where purchase_date between '2021-01-01' and '2021-01-10'
    

    You used negative logic (invalid, though), so I guess that you’re looking for fruits sold between 1st and 10t of January 2021.

    Login or Signup to reply.
  2. You can’t do this with a simple select, as that doesn’t care about what other rows are doing. But you should be able to do it in a HAVING clause to filter out based on the aggregates:

    SELECT product_name,
               min (purchase_date) AS purchase_date
        FROM sales
        GROUP BY product_name
        HAVING min (purchase_date)  >= '2021-01-01' and max(purchase_date) <= '2021-01-10'
        ORDER by product_name asc ;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search