so i have a table with hundreds records. And a have a filed name "created" type with a datetime format. Now I want to make and archive with the months. For example January, February.... etc. I need to create query to find all possible months. For example if my records start from 2011/05/01 to now I will need to fetch the months that means months 5,6,7,8,9,10,11,12.
Is there a way to that ???
If you are looking at the list of all Months present in the created field (as I understand your query) then do this:
SELECT DISTINCT(MONTH(created)) FROM posts;
The resulting set would be the list of unique months in the field. If this will complain then try:
SELECT DISTINCT(MONTH(DATE(created))) FROM posts;
You can then substitute MONTH for MONTHNAME and get names instead. I did not add the WHERE clause to these queries but you can limit the dataset you are looking at as you see fit.
For more information take a look at http://dev.mysql.com/doc/refman/5.1/en/functions.html this has a list of quite a few functions that MySQL natively provides.
Yes, use the DATE_FORMAT function and other date and time functions.
More details here
For example, if you want all your records for December 2011:
SELECT * FROM posts WHERE YEAR(created) = 2011 AND MONTH(created) = 12
Related
I have a week column with week numbers as w0, w1, w2.... I am trying to get last last six weeks data. Here's the sql query I am using.
SELECT * FROM week
WHERE uid = '9df984da-4318-1035-9589-493e89385fad'
AND report_week BETWEEN `'w52' AND 'w5'`;
'w52' is essentially week 52 in December 2015 and 'w5' is Jan 2016. The 'between' seems to not work. Whats the best way to get data from the above two weeks?
Here's the CREATE TABLE statement:
CREATE TABLE `week` (`uid` VARCHAR(255) DEFAULT '' NOT NULL,
`report_week` VARCHAR(7) NOT NULL,
`report_files_active` BIGINT DEFAULT NULL);
Essentially this table is getting populated from other table which has date column. It uses dates from other table and summarizes weekly data into this.
Any help is appreciated.
Refer to this SO Discussion which details the reasons for a problem similar to yours.
BETWEEN 'a' and 'b' actually matches to columnValue >='a' and columnValue <= 'b'
In your case w52 is greater than w5 due to lexicographic ordering of Strings - this means that the BETWEEN clause will never return a true (think about it as equivalent to saying BETWEEN 10 and 1 instead of BETWEEN 1 and 10.
Edit to my response:
Refrain from storing the week value as a string. Instead here are a couple of approaches in order of their preference:
Have a timestamp column. You can easily then use MySQL query
facilities to extract the week information out of this. For a
reference see this post.
Maintain two columns - YEAR, WEEKNO where YEAR will store values
like 2015, 2016 etc and WEEKNO will store the week number.
This way you can query data for any week in any year.
please show me table structure and DB name because it different for other, if it is any timestamp then we can use BETWEEN 'systemdate' AND 'systemdate-6'
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
how do I get month from date in mysql
I want to get month using date example 2011-04-02 so I want month april. How to get this in MySQL?
SELECT MONTHNAME(date) AS monthName for January, February...
SELECT MONTH(date) AS monthName for 1, 2...
SELECT MONTHNAME(`date`) AS month_name FROM table_name;
You can use MONTHNAME() to get the month name. If you want month number, consider to use MONTH()
You can have a much more elegant solution to this if you use a second table as a date dimension table, and join your date field to it, in order to extract more useful information. This table can contain dates, month names, financial quarters, years, days of week, weekends, etc.
It is a really tiny table, only 365(ish) rows per year of data you have... And you can easily write some code to populate this table with as much data as you require. I did mine in Excel, exported as a CSV file and then imported the data into a blank table.
It also gives lots of benefits, for example, imagine a monthly data table with the following fields (and any others you can think of!) fully populated for all the months in a given range;
Date (E.g. 2009-04-01)
Day (E.g. 1)
Day of Week (E.g. Wednesday)
Month (E.g. 4)
Year (E.g. 2009)
Financial Year (E.g. 2009/10)
Financial Quarter (E.g. 2009Q1)
Calendar Quarter (E.g. 2009Q2)
Then combining this with your own table as follows;
SELECT `DT`.`monthName`
FROM `your_table`
INNER JOIN `dateTable` as DT
ON `your_table`.`your_date_field` = `dateTable`.`theDate`
There are many other nice outputs that you can get from this data.
Hope that helps!
If I have MySQL query like this, summing word frequencies per week:
SELECT
SUM(`city`),
SUM(`officers`),
SUM(`uk`),
SUM(`wednesday`),
DATE_FORMAT(`dateTime`, '%d/%m/%Y')
FROM myTable
WHERE dateTime BETWEEN '2011-09-28 18:00:00' AND '2011-10-29 18:59:00'
GROUP BY WEEK(dateTime)
The results given by MySQL take the first value of column dateTime, in this case 28/09/2011 which happens to be a Saturday.
Is it possible to adjust the query in MySQL to show the date upon which the week commences, even if there is no data available, so that for the above, 2011-09-28 would be replaced with 2011/09/26 instead? That is, the date of the start of the week, being a Monday. Or would it be better to adjust the dates programmatically after the query has run?
The dateTime column is in format 2011/10/02 12:05:00
It is possible to do it in SQL but it would be better to do it in your program code as it would be more efficient and easier. Also, while MySQL accepts your query, it doesn't quite make sense - you have DATE_FORMAT(dateTime, '%d/%m/%Y') in select's field list while you group by WEEK(dateTime). This means that the DB engine has to select random date from current group (week) for each row. Ie consider you have records for 27.09.2011, 28.09.2011 and 29.09.2011 - they all fall onto same week, so in the final resultset only one row is generated for those three records. Now which date out of those three should be picked for the DATE_FORMAT() call? Answer would be somewhat simpler if there is ORDER BY in the query but it still doesn't quite make sense to use fields/expressions in the field list which aren't in GROUP BY or which aren't aggregates. You should really return the week number in the select list (instead of DATE_FORMAT call) and then in your code calculate the start and end dates from it.
I've got the following query on a timestamp(specified by INT(10), which kind of does what I want, but not exactly:
SELECT count(entry_date) as theCount, FROM_UNIXTIME(entry_date, '%Y-%m-%d') AS dd
FROM exp_weblog_titles
WHERE entry_date < UNIX_TIMESTAMP(NOW())
GROUP BY dd
ORDER BY dd DESC
LIMIT 7
That spits out the last 7 dates and the # of entries on those dates that are before today's date. The problem with the query I've created is, it only spits out the date if it actually has an entry on it. When in actuality, I still want that date included even if there are zero entries. Is that possible?
You will need to have a list of dates from somewhere. A lot of people create a calendar table just for this purpose with every date (or every value) that they need so that this calendar table and your data table can be joined to provide this kind of query.
You will find in the long run this is far simpler than any other solution, just takes a moment to set up.
See this article for an example of how to generate such a table.
I have several rows in a table, each containing a start date and an end date. The user has a checkbox for each month of the year. I need to determine which rows contain a date range that includes any of the user's chosen months.
It's easy to check the start & end months by, for example, MONTH(start_date) IN ($month_list), but this approach won't match any months between the two dates.
So I suppose what I'm asking is: is there a way of obtaining the inclusive months from a date range purely in SQL?
I assume you would want to include data rows where the date range spans or intersects with the selected periods - in which case, I'd shove the user selected periods into a table and do a fuzzy join, something like.....
SELECT DISTINCT at.*
FROM a_table at, user_periods up
WHERE at.start_date<=up.end_date
AND at.end_date>=up.start_date
AND up.trans_id=$SOME_VAR
(the trans_id just allows the table to be used for multiple operations)
To minimise the effort here, the user_periods table should have an index on start_date and end_date, and similar for a_table.
Can something like this help?
WHERE
MONTH(start_date) < MONTH_YOU_ARE_CHECKING and
MONTH() > MONTH_YOU_ARE_CHECKING
If you need to check all at once you can do a list of all the months and after delete from the list the month that the user choose, and after compare against the list. It will be better with a pseudocode example :)
MONTHS = 1,2,3,4,5,6,7,8,9,10,11,12
USER_SELECTED_MONTHS= 1,6,8,9,12
LIST_TO CHECK = 2,3,4,5,7,10,11
so, now you can do:
MONTH(start_date) NOT IN (2,3,4,5,7,10,11)
What do you think, could it help you?
regards