I search and get 10 records as result.I have two drop down boxes.one will have month as value and other one will have year as the value.Say those 10 records have same year and 5 have month as jan and other five has month as feb.
When user clicks feb then five ids will be passed to my query but i need to pull the younger document.2 docs were inserted on 5th of feb and other tow 10 feb and remaining one 25feb.i need to pull this 25th feb document.
how to select this using select statement?
You can extract day and time from the database and have them shown to the user so he can select the correct document, otherwise you can solve with:
SELECT *
FROM TABLE
WHERE month = 'Feb'
AND year = 2011
AND day = (select max(day) from table where month = 'Feb' and year = 2011 )
But I'm supposing a lot of information here, these infos should help me help you out:
name of table
fields and field types
Do you have a way to keep correct track of timestamps and dates?
Presumably you have some date_inserted column in your database - if so, you can add
ORDER BY date_inserted DESC LIMIT 1
This will put them in reverse date order, and LIMIT 1 will cause it to only return 1 result
This should work:
SELECT *
FROM `table`
WHERE MONTH(`insert_date`) = 2
AND YEAR(`insert_date`) = 2011
ORDER BY `insert_date` DESC
LIMIT 1;
Note: the above assumes you have a field in your table for storing the date on which the document was created/inserted. Please replace insert_date and table in the above query with the respective column name and table name.
EDITED after this comment "date stores date,month stores month and year stores year"
SELECT *
FROM `table`
WHERE `month` = 2
AND `year` = 2011
ORDER BY `year` DESC, `month` DESC, `date` DESC
LIMIT 1;
I've assumed that in the month column you are storing numbers, 1 for Jan, 2 for Feb and so on. If however you are storing the 3-letter month name, then instead of "`month` = 2" please use this:
MONTH(STR_TO_DATE(`month`, '%b')) = 2
Hope this should work.
Related
I am trying to get a COUNT of the last 12 months of appointments grouped by month for output into a chart. The following works fine but I need it to return 0 if no results for each month.
$query = "SELECT COUNT(id) as total_month FROM appointments WHERE created >= DATE(NOW()) - INTERVAL 365 DAY GROUP BY Month(created)";
$query = $mysqli->real_escape_string($query);
if($result = $mysqli->query($query)){
while($row = $result->fetch_array())
{
$month_total_appointments .= $row['total_month'].',';
}
}
echo $month_total_appointments;
================================================================
Simple table structure and example for appointments Table
id customer_name created
1 John 2020-05-01 08:00:00 <= stored as datetime
2 Mike 2020-04-01 09:00:00
3 Steve 2020-02-01 10:00:00
Output would be 0,0,0,0,0,0,0,0,1,0,1,1
======================================================
Current output is: 1,1,1
I've read some use a month table and LEFT JOIN but everything i've tried doesn't seem to work. Can anyone help please?
You won't get zeroes for rows that aren't there. Grouping combines rows that match particular criteria, but it can't fabricate them out of nothing.
That's why it's typical to include the grouping criteria in the results:
SELECT COUNT(id), MONTH(created) AS created_month
FROM appointments
WHERE created >= DATE(NOW()) - INTERVAL 365 DAY
GROUP BY created_month
Then you can expand that in your application code to fill in the missing values. The alternative is you need a fully populated list of all possible dates to JOIN against.
Keep in mind the MONTH() thing will wrap around and group January 2020 with January 2021. You may want to split this up:
SELECT COUNT(id), YEAR(created) AS created_year, MONTH(created) AS created_month
FROM appointments
WHERE created >= DATE(NOW()) - INTERVAL 365 DAY
GROUP BY created_year, created_month
I have the following table with dummy values in mysql database:
id cnic amount depositDate receivedBy receivingZone remarks
1 11111 10000 01-Nov-2019 11111 1 Ok
2 11111 10000 07-Nov-2019 11111 1 ok
Now i want to get the sum of amount from the table for specific year (2019 in this case) where the year came from current timestamp (it may be 2020, 2021 etc depends on the current date)
Any help plz
You can use the YEAR function to get the year of the depositDate column and also the current year and then sum only the values which match:
SELECT SUM(amount) AS amount
FROM yourtable
WHERE YEAR(STR_TO_DATE(depositDate, '%d-%b-%Y')) = YEAR(CURDATE())
You can try below -
select sum(amount)
from tablename
where year(depositdate)=year(now())
I would write the WHERE clause to be sargable:
SELECT SUM(amount)
FROM yourTable
WHERE depositDate >= DATE_FORMAT(NOW() ,'%Y-01-01') AND
depositDate < DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 YEAR) ,'%Y-01-01');
This approach, while a bit more verbose than the other answers which use the YEAR() function, would allow an index on the depositDate column to be used.
Based on your sample year, we need to recognize first the date using str_to_date
select sum(amount)
from tableA
where year(now()) = year(str_to_date(depositdate, '%d-%b-%Y'))
I have a MySQL DB where I store dates in the following format
2017-04-03
I need to split or search dates to get all dates and records for January, Feb, March and so on in between all the dates I have in DB
$result = mysql_query("SELECT * FROM lbs_trace_etrack WHERE MONTH(lbs_date) = MONTH(CURDATE()) AND YEAR(lbs_date) = YEAR(CURDATE()) ORDER BY lbs_date DESC, lbs_time DESC");
I use the above query to search Current month and year. I am drawing up a graph that shows me stats from each month this is the reason I want each months count
I need to place the counts for the search in the following format.
var seriesData = [{
name: 'Hijackings',
data: [Value Jan, Value Feb, Value March, and all the other months ]
}, {
If anyone can just help me with the filter on each month query would help me greatly
Try this query:
select count(*) as total, MONTH(lbs_date) as track_month, YEAR(lbs_date) as track_year
FROM lbs_trace_stack t
GROUP BY track_year, track_month
Or if you only want month or only want year, you have just to remove
MONTH(lbs_date) and track_month --> if you want to see the year remove this
YEAR(lbs_date) and track_year --> if you want to see the month remove this
from the select part and group by part.
In addiction, if you want to filter on one or more months you can of course use the where statement, to set up your filter.
There are a several ways to write some where condition that do the same things, for example:
SELECT COUNT(*) as total, MONTH(lbs_date) as track_month
FROM lbs_trace_stack t
-- WHERE track_month = 2 -> February
-- WHERE track_month > 2 -> Form March
-- WHERE track_month = 2 OR track_month = 3 -> February or March
-- WHERE MONTHNAME(lbs_date)='February' --> if you want to use month name
GROUP BY track_month
I have found that this query works
$query = "SELECT rep_date FROM `bureau` WHERE MONTH(rep_date) = 1 AND type = 'Overdue'";
$result = mysql_query($query);
echo " ".mysql_num_rows($result)." "
?>
<?php
while($rows=mysql_fetch_array($result)){
?>
Using the MONTH(rep_date)=1 will filter all January changing 1 to 2 will do Feb and so on
I want to list the scores, by month, for something that happened over the last 12 months. I noticed my query below was combining the results of the first partial month with the results of the last partial month. That is, my July report combined July 9-31, 2015 with July 1-8 2016 (now is July 8). I only want the latest month to represent the latest year. Here is what I was using...
$query = "SELECT record_id,
time_scored,
MONTH(time_scored) as month_added,
score, comment
FROM records
WHERE score IS NOT NULL AND
time_scored >= DATE_SUB(curdate(),INTERVAL 12 MONTH)
ORDER BY time_scored DESC";
Any help would be appreciated. Thanks!
Subtract 12 months from next months 1st day
$query = "SELECT record_id,
time_scored,
MONTH(time_scored) as month_added,
score, comment
FROM records
WHERE score IS NOT NULL AND
time_scored >= DATE_SUB(DATE_ADD(subdate(curdate(), (day(curdate())-1)), INTERVAL 1 MONTH),INTERVAL 12 MONTH)
ORDER BY time_scored DESC";
I have to filter data for last 3 months from current date, so that would be to fetch data from Aug to Oct. But value exist for October only in mysql table, so now i want to display record in following format:
Month Values
Aug 0
Sept 0
Oct 10
But my query only shows October month records as i dont have record for previous 2 months.
How can i do this. Following is my query.
SELECT
CASE WHEN COUNT(DISTINCT(user_analytics_id)) > 0 THEN COUNT(DISTINCT(user_analytics_id)) ELSE 0 END as pic_views,
YEAR(user_profile_viewed_date) AS pic_viewed_year,
MONTHNAME(user_profile_viewed_date) as pic_viewed_month
FROM (`user_analytics`)
WHERE `user_id` = '1' AND `view_type` = 'picture'
AND `user_profile_viewed_date` BETWEEN '2010-07-28 04:23:56' AND '2010-10-28 04:23:56'
GROUP BY MONTH(user_profile_viewed_date) ORDER BY MONTH(user_profile_viewed_date) ASC
The above query is not working as i want it to. So pls help me on this..
Create another table with numbers 1 .. 12 and LEFT JOIN your table to it.