简体   繁体   中英

Trying to find this day last year. Ex: Get the 1st Friday of October, not the October the 4th

I'm not sure this is even possible without using PHP, but I'd love to try.

I have a database that looks like this (a bunch of other stuff, but this is all that is relevant:

Date_Day (is a range from 1 to 31 with no trailing 0)

Date_Month (is a range from January to December, not numerical)

Date_Year (is the year in 4 digit format, ex: 2005)

Total (number with 2 decimal places)

I know the way the dates are stored is awful, but this is the database I was given. If there is a query that I could use these columns to create an actual DATETIME column, I would happily do it, I just don't know what that query looks like.

I have this query that returns the Total sales amount for this day for all previous years:

SELECT 
    Date_Year, Date_Month, SUM(Total) 
FROM 
    tablename 
WHERE 
    Date_Year < YEAR(CURDATE()) 
AND 
    Date_Month = MONTHNAME(CURDATE()) 
AND 
    Date_Day = DAY(CURDATE()) 
GROUP BY 
    Date_Year, Date_Month

So if I run this today, I get the daily totals for October 4th for all previous years. The issue is that in sales, this isn't very helpful for comparing growth. What I really need is the daily totals for the 1st Friday in October for all previous years.

Is this possible without having to rely on PHP? If so, I would be very grateful for your help.

Thank you.

You might be looking for DAYOFWEEK()

Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard.

mysql> SELECT DAYOFWEEK('2007-02-03');
     > 7
SELECT 
    Date_Year, Date_Month, SUM(Total) 
FROM 
    tablename 
WHERE 
    Date_Year < YEAR(CURDATE()) 
AND 
    Date_Month = MONTHNAME(CURDATE()) 
AND 
    Date_Day = DAY(LAST_DAY(CURDATE()) - ((28 + WEEKDAY(LAST_DAY(CURDATE())) - 4)))
GROUP BY 
    Date_Year, Date_Month

maybe this will help

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM