I am wanting to show current month data. But when I am using this query, then generating extra single string from query.
$queryCurentMonth = $this->Bookings->find('all')
->where(["MONTH(Bookings.created)" => "MONTH(CURRENT_DATE())"]);
Generating :
SELECT
*
FROM
`bookings` `Bookings`
WHERE
MONTH(`Bookings`.`created`) = 'MONTH(CURRENT_DATE())'
This = 'MONTH(CURRENT_DATE())' , it is generating blank data. How we can perfect this query.
MySQL is treating your RHS value as string in
MONTH(`Bookings`.`created`) = 'MONTH(CURRENT_DATE())'
'MONTH(CURRENT_DATE())' shouldn't have single quotes around it. Instead it should be like this
MONTH(`Bookings`.`created`) = MONTH(CURRENT_DATE())
Try to compare year also as function MONTH() returns only a number 1 through 12, the query would return all records for a Month of all years, rather than only the current year. Use both MONTH(), YEAR() to compare months for the current year.
MONTH(`Bookings`.`created`) = MONTH(CURDATE()) AND YEAR(`Bookings`.`created`) = YEAR(CURDATE())
Finally, I have got a solution. it is working finely now.
$queryCurentMonth = $this->Bookings->find('all')
->where(["MONTH(Bookings.created)" => date("m")]);
Related
I am trying to grab all the records for the month. The string I have to query with is in this format 2019-01-12. The record I am querying for is a DateTime record so it has a format like this 2018-08-11 13:39:22.959330.
So I am trying to structure a query that would achieve this
Score.where('user_id = ? AND date_closed.strftime("%Y-%m) = ?', current_user.id, date)
Where date is the 2019-01-12 string. The above code produces the error
FUNCTION date_closed.strftime does not exist
I did google but was unable to locate something that achieved this. Most solutions involved searching inside a range of dates, I would really like to try to keep the search method the same.
You have the DATE_FORMAT function for that https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
DATE_FORMAT(date_closed, "%Y-%m")
EDIT: you'll have to also format the date you are passing to the query
You can use mysql data functionos YEAR and MONTH:
Score.where('user_id = ? AND YEAR(date_closed) = ? AND MONTH(date_closed) = ?', current_user.id, date.year, date.month)
I work for a gun club and we are trying to find the total number of targets shot at during a specific year. The table contains totals from years 2000-2018 and I am trying to write a query that will look at the string for the date of the shoot which is in a format like this 2010-06-13 00:00:00.000 I just care about the year so I created this query:
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND ShootDate LIKE '2007-%%-%% 00:00:00.000'
If I run the query up to the AND clause it works and returns a total. However, I get a null value if I highlight the whole thing. I have tried variations of the string as well. Such as this '2007%' and this '2007-- %'
Not sure what I am missing. Any help is appreciated.
Don't convert to string to query for a year, use YEAR() function instead:
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND YEAR(ShootDate)=2007 -- MySQL
You could also use a range query
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND ShootDate BETWEEN '2007-01-01' AND '2007-12-01 23:59:59.999'
Note: The above assumes that you do not store dates as strings. The function to use depends on RDBMS. In MS SQL Server you would use DATEPART(year, ShootDate) = 2007
I have a query where I need to select entries only where their month is equal to a certain month.
Each entry has the date saved in the ymd format (20140211).
I have tried the following, but it doesn't recognise the month.
AND (MONTH(matrix.col_id_3) = '1' OR MONTH(matrix.col_id_4) = '1')
Is this due to the date format? I am stuck with this format as its part of the CMS I use.
Any help would be fantastic.
if you can use the default date column type (why?) so you have to convert your column
i.e.
... MONTH(STR_TO_DATE(matrix.col_id_3,'%Y%m%d')) = 1 ...
probably your dates are stored as strings, so you could use the following
.... SUBSTRING(matrix.col_id_3, 5, 2) = '01' ...
I have a table with the following format:
offer_id consumer_id date
1 1 1282454200
1 1 1282453200
2 2 1282453240
1 3 1282455200
2 1 1282453210
"date" is in unix format.
I need to count all of the daily entries, so if I have 10 entries from yesterday and 8 entries from today, I should get:
2013-06-23 10
2013-06-24 8
This is part of my work on trying to optimize code, so far I have been doing this via PHP code, but you can imagine what happens with a growing database :). This is my php (codeigniter) attempt that I'm trying (unsuccessfully) to translate into mysql:
foreach ($offers as $item) {
$date = $item->date;
$day_date = date("Y-m-d", $date);
$day_start = strtotime(date("Y-m-d 00:00:00", $date));
$day_end = strtotime(date("Y-m-d 23:59:59", $date));
if (!in_array($day_date, $day_array)) {
$day_array[] = $day_date;
$this->db->where("date >=", $day_start);
$this->db->where("date <=", $day_end);
$this->db->from("offers_consumers_history");
$total_points = $this->db->count_all_results();
$db_date = array($day_date, $total_points);
$data[] = $db_date;
}
}
I basically grabbed all of the entries in a previous query and went through every date, if the date isn't in my final array, I had to it by counting all results from 00:00:00 to 23:59:59.
Looking for help in building equivalent SQL code.
You could use this SQL query:
SELECT DATE(FROM_UNIXTIME(date)), COUNT(*)
FROM offers_consumers_history
GROUP BY DATE(FROM_UNIXTIME(date))
Please see fiddle here.
Try like
SELECT count(*) as cnt , date FROM `my_table` GROUP BY date
Then you can change them as your required format.It is simple and same that to change the dates into FROM_UNIXTIME and then counting
If I have right understood your question, group by is what you need
I'm trying to work with a database of unemployment figures from the department of labor statistics' data (available at ftp://ftp.bls.gov/pub/time.series/la/)
I need to get the last 12 months of data for any given state, which is trickier then just selecting all data from the last year as they don't always have the last few months of data in yet (right now, the last month's worth of data is November 2010).
I know which record is the newest, and the date fields I have in the database to work with are:
period_name (month name)
year
period (M01, M02, etc for January, February)
My current SQL, which pulls data from a bunch of JOINed tables, is:
USE unemploymentdata;
SELECT DISTINCT series.series_id, period_name, year, value, series.area_code,
footnote_codes, period_name, measure_text, area_text, area_type_text
FROM state_overview
LEFT JOIN series ON state_overview.series_id=series.series_id
LEFT JOIN footnote ON state_overview.footnote_codes = footnote.footnote_code
LEFT JOIN period ON state_overview.period = period.period
LEFT JOIN measure ON series.measure_code = measure.measure_code
LEFT JOIN area ON series.area_code=area.area_code
LEFT JOIN area_type ON area.area_type_code=area_type.area_type_code
WHERE area_text = 'State Name' AND year > 2009
ORDER BY state_overview.period, measure_text;
Any idea?
Since you have textual values to work with for month and year, you'll need to convert them to MySQL-formatted DATE values and can then let MySQL calculate the last year interval like so:
SELECT ... WHERE STR_TO_DATE(CONCAT(period_name,' 1 ',year),'%M %d %Y') >= DATE_SUB(STR_TO_DATE(CONCAT(most_recent_period_name,' 1 ',most_recent_year),'%M %d %Y'), INTERVAL 1 YEAR) ...;
The CONCAT() function is just building a string like "Month 1 YYYY", and the STR_TO_DATE() function is taking that string and a formatting string to tell it how to parse it, and converting it into a DATE.
Note: This query probably sucks index-wise but it should work. : )
I think a few changes to WHERE clause should do it, but for effeciency/simplcity you should also add MAX(year) to the SELECT section.
SELECT ...... MAX(year) as max_year .....
WHERE area_text = 'State Name'
AND year >= max_year - 1
AND period >= (SELECT MAX(period) WHERE year = max_year)
ORDER BY state_overview.period, measure_text;
You can store the year and month as a date, even though you don't have the day information. Just use the first of each month.
{2009, 'M1'} => 2009-01-01
{2009, 'M2'} => 2009-02-01
{2009, 'M3'} => 2009-03-01
This makes date arithmetic much easier than dealing with substrings of (potentially dirty) data. Plus (and this is big), you can index the data much more effective. As a bonus, you can now extract a lot of extra goodies using DATE_FORMAT such as month names, nr of days in month etc.
Does all states have data for all months, and is the data updated at the same time? The answer to that question dictates what query strategy you should use.
The best way is to take the strtotime ($a) of correct 1 year ago and then, when fetching the value from database then find the strtotime ($b) of the date in each result. Now
if($b < $a){
continue;
}
else {
//do something.
}