Home > database >  Date time stamp query in SQL
Date time stamp query in SQL

Time:08-17

I am a SQL beginner and had a query to find the ID of the person who booked the last sales in MAY 2015, the occurred_at column is a datetime (2015-10-06 17:31:14) and I do not know how to get the last sales booked in May 2015 from that.

This is my query below and it says there is no column as Sales_Date. Please help

SELECT 
    ID, 
    CAST(occurred_at AS time) AS sales_time,
    CONCAT(' ', CAST(occurred_at AS DATE)) AS Sales_Date,
    extract(year from sales_date) AS year, 
    extract(month from sales_date) AS Month  
FROM
    <table name >
WHERE 
    year = 2015 AND month = 05 
ORDER BY 
    sales_time DESC

CodePudding user response:

If you want to get the last sales, why not just use MAX(occured_at) and year = 2015?

CodePudding user response:

You also need to extract the year and month on your where clause.

SELECT ID , CAST(occurred_at AS time ) AS sales_time  ,
       CONCAT ( ' ' , CAST(occurred_at AS DATE) ) AS Sales_Date ,
       extract ( year from sales_date) AS year , 
       extract ( month from sales_date) AS Month  
from <table name >
where extract(year from sales_date) = 2015 and extract(month from sales_date) = 5 
order by sales_time desc 
  • Related