MS SQL Server Query Date functions to MySQL - mysql

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.

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'));

Related

MySQL Selecting Dynamic Date Range

I have a datetime column and I want to select all rows from the previous 2 complete months (Sept and Oct, currently). Manually I could compose this query as:
where date_column between '2018-09-01' and '2018-10-31'
but how can I do this programmatically so the end date is always correct? I was thinking
where date_column between concat(substr(now() - INTERVAL 2 month, 1, 7), '-01') and concat(substr(now() - INTERVAL 1 month, 1, 7), '-31')
but the 31 will be incorrect for November, February, etc.
You could format the date and just hard code the day to be 1:
date_column BETWEEN
DATE_FORMAT(NOW() - INTERVAL 2 MONTH, '%Y-%m-01') AND
DATE_FORMAT(NOW(), '%Y-%m-01')

Getting the month to show date name rather than number when pulling each month in the year

I am pulling data that lists each month of the year but the month column states the first day of each year, how can I make this show the full month name?
Here is some of what I have. I read similar questions and tried to add in what it stated everywhere but I couldn't get it work, help?
SELECT a.MonthDate
,Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) As ScrapPct
,0.05 As ScrapTarget
,sum (a.GrossPcs) As 'Total Parts Cast'
,sum (a.ScrapPcs) as 'Total Parts Scrap'
,CASE
WHEN Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) <= 0.05 THEN 1
WHEN Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) >= 0.9*.05 THEN -1
ELSE 0
END
AS Status
FROM
(
SELECT DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0) As MonthDate
,Count(b.BOOKING_ID) As ScrapPcs
, 0 As GrossPcs
FROM dbo.CPC_BOOKING b
WHERE b.CreationProdDate Between DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) AND DateAdd("d", -1, GetDate())
and CPC_BookingTyp_ID in (2,8)
and ManufacturingPlant in (90002604,90017699, 90017705)
GROUP BY DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0)
UNION ALL
SELECT DATEADD(month, DATEDIFF(month, 0, n.ProductionDate), 0) As MonthDate
,0 As ScrapPcs
,Sum(n.Quantity) As GrossPcs
FROM [NORIS].[dbo].[MDL_Data_Ultimate] n
WHERE n.ProductionDate Between DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) AND DateAdd("d", -1, GetDate())
and n.ManufacturingPlantGroup = 1
GROUP BY DATEADD(month, DATEDIFF(month, 0, n.ProductionDate), 0)
) a
group by a.MonthDate
Thanks in advance, anything helps
For MySQL:
https://www.w3resource.com/mysql/date-and-time-functions/mysql-monthname-function.php
Use the MONTHNAME function as per the example on that webpage.
SELECT MONTHNAME(a.MonthDate)
For MS SQL Server:
If you want the month name use this in the derived table:
SELECT datename(month,DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0)) As MonthDate
That is, you want to apply the datename(month, date)function to the first column of both unioned queries.

How to find data from a previous month in sql starting from day 1 in the SELECT in sql?

SELECT
team, team_name, COUNT(*) AS c
FROM
[helpdesk].[dbo].[inpc] , helpdesk.dbo.teams
WHERE
team = teams.id
AND st IN (4, 5)
AND CONVERT(VARCHAR(10), dd_1, 102) > DATEADD(month, -1, GETDATE())
GROUP BY
team, team_name
Your question is really a painful SQL Server date olympics question. We can phrase the requirement of the previous month as a date on or after the first of the previous month and strictly before the first of the current month.
SELECT
team,
team_name,
COUNT(*) as c
FROM [helpdesk].[dbo].[inpc], helpdesk.dbo.teams
WHERE
team = teams.id AND
st IN (4,5) AND
dd_1 >= DATEADD(month, DATEDIFF(month, 0, DATEADD(month, -2, GETDATE())), 0) AND
dd_1 < DATEADD(month, DATEDIFF(month, 0, DATEADD(month, -1, GETDATE())), 0)
GROUP BY
team,
team_name;
Also, as others have pointed out, you should use explicit join syntax. I'm not sure your current join even makes sense, as it appears to be a cross join.

How do i select all records for the next 3 months including the current one when it turns into a new year

I am trying to select every record between current month and the next 2 months but I am not able to because the year will be changing from 2016 to 2017.
For ex.
I want to get all the records from November 2016 to January 2017.
The current query (shown below) i have has worked fine until this month because November 2016 + 2 months = Jan 2017.
select * from dateTable
where month(t2.`END_DATE`) between month(curdate()) and
month(DATE_ADD(curdate(), INTERVAL 2 MONTH))
and year(t2.`END_DATE`) = year(curdate());
This returns 0 rows because this cannot handle having two years, 2016 and 2017.
How would I go about doing this?
This should be what you need, although there are probably a number of ways of doing this
select * from dateTable
where `END_DATE` BETWEEN DATE_FORMAT(NOW() ,'%Y-%m-01')
AND LAST_DAY(DATE_ADD(NOW(), INTERVAL 2 MONTH))
The result of this query will demonstrate the dates being generated
SELECT DATE_FORMAT(NOW() ,'%Y-%m-01') as from_date,
LAST_DAY(DATE_ADD(NOW(), INTERVAL 2 MONTH)) as to_date
Today this will generate
from_date to_date
2016-11-01 2017-01-31
Try to use full datetime with DATE_ADD and DATE_DIFF functions.
select * from dateTable where t2.`END_DATE`
between DATEADD(month,
DATEDIFF(month, 0, getdate() -- get difference to first day
), 0)
and DATEADD(month, 2, -- add 3 months interval to get first day of third
DATEADD(month,
DATEDIFF(month, 0, getdate() -- get difference to first day
), 0))
If you have to remove the first day from last month use DATEADD again and remove 1 second to get 23:59:59

MySQL: Select with first and last day of previous month

Using PhpMyadmin, I have this sentence working:
SELECT id_order as Ref FROM t_orders WHERE DATE(invoice_date) = CURDATE()
Now I want to reemplace "current date" (CURDATE) for the first day of previous month in advance.
The answer of Ankit Bajpai solved my problem (thank you):
SELECT id_order as Ref FROM t_orders WHERE DATE(invoice_date) >= concat(date_format(LAST_DAY(now() - interval 1 month),'%Y-%m-'),'01');
in MYSQL you can try the below
First day of Previous Month
select last_day(curdate() - interval 2 month) + interval 1 day
Last day of Previous Month
select last_day(curdate() - interval 1 month)
First day of Current Month
select last_day(curdate() - interval 1 month) + interval 1 day
Last day of Current Month
select last_day(curdate())
Try following query:-
SELECT id_order as Ref
FROM t_orders
WHERE DATE(invoice_date) >= concat(date_format(LAST_DAY(now() - interval 1 month),'%Y-%m-'),'01');
For MS SQL Server:
DECLARE #firstDayOfLastMonth DATETIME = DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
DECLARE #lastDayOfLastMonth DATETIME = DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
SELECT #firstDayOfLastMonth;
SELECT #lastDayOfLastMonth;
After reading closely... you want the entire month, of the previous month. You can do this:
SELECT id_order as Ref FROM t_orders
WHERE
DATE(invoice_date) >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
AND
DATE(invoice_date) <= DATEADD(month, DATEDIFF(MONTH, 0, GETDATE()), -1)
OR
SELECT id_order as Ref FROM t_orders
WHERE
MONTH(DATE(invoice_date)) = MONTH(DATEADD(MONTH,-1,GETDATE()))