I am currently developing a platform where I need 3 SQL queries to return all records between Year/Month/Week to date.
The queries have to work dynamically without hard-coded dates, please bear with me if i should split these up into 3 questions, i think they are very relatable and that's why i put all 3 in here :)
1: Year To Date
I tried this SQL query according to this question about Year To Date but I am receiving an error:
Incorrect parameter count in the call to native function 'DATEDIFF'
SELECT coins_daily_date, coins_daily_high, coins_daily_low, coins_daily_close, coins_daily_volume
FROM coins_daily
WHERE coins_daily_date BETWEEN DATEADD(yy, DATEDIFF(yy,0,GETDATE()), 0) AND GETDATE()
ORDER BY coins_daily_date ASC
2: Month To Date
I tried different things with the month function but could not figure out how to achieve/build a correct month to date SQL query.
3: Week To Date
Honestly, I have no idea where, to begin with, this one.
Works fine going back 1 year
SELECT coins_daily_date, coins_daily_high, coins_daily_low, coins_daily_close, coins_daily_volume
FROM coins_daily
WHERE coins_daily_date >= DATE_ADD(NOW(),INTERVAL -1 YEAR
ORDER BY coins_daily_date ASC
I hope someone can help or point me in the right direction :)
Best regards!
GETDATE() is for MsSQL. Use NOW() for current datetime or curdate() for current date.
For year-to-date :
SELECT coins_daily_date, coins_daily_high, coins_daily_low, coins_daily_close,
coins_daily_volume
FROM coins_daily
WHERE YEAR(coins_daily_date) = YEAR(NOW())
AND coins_daily_date <= NOW()
ORDER BY coins_daily_date ASC
For month-to-date :
SELECT coins_daily_date, coins_daily_high, coins_daily_low, coins_daily_close,
coins_daily_volume
FROM coins_daily
WHERE YEAR(coins_daily_date) = YEAR(NOW())
AND MONTH(coins_daily_date) = MONTH(NOW())
AND coins_daily_date <= NOW()
ORDER BY coins_daily_date ASC
For week-to-date :
SELECT coins_daily_date, coins_daily_high, coins_daily_low, coins_daily_close,
coins_daily_volume
FROM coins_daily
WHERE YEAR(coins_daily_date) = YEAR(NOW())
AND WEEK(coins_daily_date) = WEEK(NOW())
AND coins_daily_date <= NOW()
ORDER BY coins_daily_date ASC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.