MS SQL Server Query Date functions to MySQL

sql_newbie :

I have this MS SQL Server query:

SELECT  DATEPART(MONTH, si.score_date),
        MAX(si.score_value)
FROM score_info AS si
WHERE si.score_date >= DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
GROUP BY DATEPART(MONTH, si.score_date);

Now I'm having a hard time converting this query to MySQL especially this part:

DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))

So far here's what I've converted from MS SQL Server query to MySQL query:

DATEPART(MONTH, si.score_date)

to

EXTRACT(MONTH FROM si.score_date)

Please help me as I'm on my learning stage. Thank you so much.

GMB :

This T-SQL expression:

DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))

Gives you the first day of the month, 3 months ago (as of today March 30th, that's December 1st).

In MySQL you can get the same result like so:

DATE_FORMAT(CURRENT_DATE, '%Y-%m-01') - INTERVAL 3 MONTH

Also, EXTRACT(MONTH FROM si.score_date) can be shorten as MONTH(si.score_date) (the MONTH() function exists in both MySQL and TSQL, by the way). But note that presumably, you want to keep the year part as well, in case your data spreads over severl year.

I would write your query as:

SELECT  
    DATE_FORMAT(si.score_date, '%Y-%m-01') year_month,
    MAX(si.score_value) max_score
FROM score_info AS si
WHERE si.score_date >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-01') - INTERVAL 3 MONTH
GROUP BY DATE_FORMAT(si.score_date, '%Y-%m-01'));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=395198&siteId=1