I have a table with a datetime column with multiple dates in. I want to output the month and year for every row that exists only once. e.g "April 2017, April 2018, May 2018, June 2018"
I've managed to get the below working, this displays "April May June", but it needs to display April twice as it is in different years and I also want to display their respective years.
<?php $results = mysqli_query($link, 'SELECT DISTINCT MONTH(date_added) AS "Month" FROM payments') or die("Query fail: " . mysqli_error($link)); ?>
<?php foreach($results as $result) :?>
<?php $monthText = date("F", strtotime("2001-" . $result['Month'] . "-01")); ?>
<?= $monthText ?>
<?php endforeach; ?>
I've been researching for hours and not manged to find a solution that works.
You can apply the distinct keyword to a combination of fields:
SELECT DISTINCT YEAR(date_added) AS "Year", MONTH(date_added) AS "Month" FROM payments
You have to group:
SELECT MONTH(`date_added`) AS `Month`, YEAR(`date_added`) AS `Year`
FROM `payments`
GROUP BY `Month`, `Year`
With the later versions and strict rules you will not get the right response from either of the above answers as GROUP BY operates before the SELECT part of the query and hence it does not respond to aliases.
You need
SELECT DISTINCT MONTH(`date_added`) AS `Month`, YEAR(`date_added`) AS `Year`
FROM payments GROUP BY MONTH('date_added`), YEAR(`date_added`)
Related
I have a table where I need to count all present to show how many attendance student have
In my table have Following Column
school id
Student id
year
Month
Status
day_1
day_2
day_3
To
day_31
entry goes once in a month. Like
if new month new row create
else update in day_ 1 day_2 day_3 etc.
Here's a different trick. Although it's for MySql 8.0+
Concatinate the day_n fields into a string.
Then remove all the characters that aren't 'P' from that string.
Then the character length of the remaining string will be the total 'P'.
SELECT school_id, student_id, month, year,
CHAR_LENGTH(
REGEXP_REPLACE(
CONCAT_WS('' -- using concat_ws because concat returns null when one of the fields is null
, day_1
, day_2
-- add more day_n here
, day_31),'[^P]+','')) AS present
FROM YourTable
A more conventional approach might look something like this:
student_id,
attendance_date
You can made a query to get the IDs of all students,
$sql2 = "SELECT distinct id from table";
$query = $this->db->query($sql2);
foreach ($query->result() as $innerrow) {
HERE YOU USE THE SYNTAX OF NEXT CODE-BLOCK
}
Inside the foreach loop you can use the id with $row->id to generate another sql query
with an where clause.
$sql = "SELECT table.* from table where id = ".$row->id;
$query = $this->db->query($sql);
foreach ($query->result() as $row) {
print your data
}
write query to find the attendance with present like
select (if(day_1 in('P'),1,0)+if(day_2 in('P'),1,0)+if(day_3 in('P'),1,0)+if(day_4 in('P'),1,0)+if(day_5 in('P'),1,0)+if(day_6 in('P'),1,0) + if(day_7 in('P'),1,0)+if(day_8 in('P'),1,0)+if(day_9 in('P'),1,0)+....+if(day_n in('P'),1,0)) as day_present from tbl_name
But the if condition for all 31 days or 30 days as per months days
just try it once in your mysql query editor You will get the exact result..
In codeigniter
$result = $this->db->select("(if(day_1 in('P'),1,0)+if(day_2 in('P'),1,0)+if(day_3 in('P'),1,0)+if(day_4 in('P'),1,0)+........+if(day_n in('P'),1,0)) as present, school_id, student_id,year, month, status");
$this->db->get('table_name');
I am trying to make a weekly statistics for user registration. It should work for weekly. There are total of seven days in a week. I want to print the number of users who are registered every day in the week on the screen.
For example:
Number of users who registered on Monday = 38
Number of users who registered on Tuesday = 11
.... .... and this list will only list the week we were
I created a sql query like the following:
SELECT WEEKDAY(registerTime)+1, count(*)
FROM users group by WEEKDAY(registerTime)
ORDER BY WEEKDAY(registerTime)
But the outcome of this question is very different. This total shows the number of users who registered on Monday for every year .
You want to limit users to only this week so you don't get everything:
SELECT WEEKDAY(registerTime)+1, count(*)
FROM users
WHERE WEEKOFYEAR(registerTime) = WEEKOFYEAR(CURDATE())
AND YEAR(registerTime) = YEAR(CURDATE())
group by WEEKDAY(registerTime)
ORDER BY WEEKDAY(registerTime);
Basically you match the year and week of year with what you need. That should be enough.
Try like this :
SELECT datepart(week, registerTime), count(*) FROM Users GROUP BY datepart(week, registerTime)
You can also use Php code for this purpose. First make array of days and then you can get registered users for each day through that array
function today()
{
return date("Y-m-d");
}
function last_seventh_day()
{
return date("Y-m-d",strtotime("-7 days"));
}
$days = ['Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday'];//Array that stores all days
foreach($days as $day)
{
$sql = "select * FROM users where day = '$day' and date_column between " .today() . "and" .last_seventh_day() ;
}
I have updated my answer. I hope this will work for you!
i want to make report that can be viewed by weekly , monthly and yearly.
for example:
i want to see who enrolled by weekly , or i want to see who enrolled in this month or year and also about the payments. i want to see the enrollee this june . i want to see the enrollee this 2010 by using a dropdown search.
// this is my code for my weekly report which i want to see students who enrolled last week but i dnt know if my code is correct.
$datetoday=date("Y-m-d");
$result = mysql_query("
SELECT enrollee_info.*, payments.* from enrollee_info
INNER JOIN payments on payments.enrollee_id=enrollee_info.e_id
WHERE enrollee_info.category='Walk In'
AND DATE_FORMAT(payments.entrydate , %Y-%m-d')>=SUBDATE('".$datetoday."' , INTERVAL 7 DAY)");
with monthly and yearly , for example i want to see who enrolled this month etc. and i want to see who enrolled this year by using a dropdown that you can select month or the year you want to search.
Take a look at the manual regarding the acceptable units for INTERVAL. You can simply use a switch to determine the range for your records.
In your drop down you'll have week, month or year. You can then use a switch to prepare your statement.
$sql = "SELECT enrollee_info.*,
payments.*
FROM enrollee_info
INNER JOIN payments
ON payments.enrollee_id = enrollee_info.e_id
WHERE enrollee_info.category = 'Walk In'
AND payments.entrydate >= Subdate(Curdate(), ";
switch ($range) {
case "month":
$sql .= 'INTERVAL 1 MONTH';
break;
case "year":
$sql .= 'INTERVAL 1 YEAR';
break;
//if no match, use week
default:
$sql .= 'INTERVAL 1 WEEK';
}
$sql .= ')';
Which would create a statement like this:
SELECT enrollee_info.*,
payments.*
FROM enrollee_info
INNER JOIN payments
ON payments.enrollee_id = enrollee_info.e_id
WHERE enrollee_info.category = 'Walk In'
AND payments.entrydate >= Subdate(Curdate(), INTERVAL 1 week)
If possible, try to avoid fetching all columns from each table and use a column list.
Please help my knowledge is limited and I have been struggling with this for almost a week now.
I have a table which allows the user to post to it. I want to display each month that has a post in it e.g.
DEC
OCT
SEPT
AUG
FEB
However, if there has been multiple post in a single month, I only want that month to be displayed once, how do I do this?
So far I have created this:
$months = mysql_query("SELECT article_id, content, DATE_FORMAT(date, '%M')
AS date
FROM article
ORDER BY article_id
DESC
LIMIT 12");
while($row = mysql_fetch_array($months)){
echo "" . $row['date'] . "<br/>";
}
Each month that has a post is displayed the number of times posts have been made, obviously this is not what im after :(
Use the DISTINCT keyword:
SELECT DISTINCT MONTH(date) FROM article ...
Try this:
SELECT DISTINCT(MONTHNAME(date)) as post_month
FROM article
DISTINCT removes duplicates from the applied columns.
I run an online magazine and would like a dead-simple way to track 3 metrics:
How many comments are left each day.
How many links my users submit.
How many new members I get each day.
This information is all my database, I'm just not sure how to get it out.
I have a "comments" table with about 3500 comments. Each comment gets a row in the table. One of the columns in the table is "timestamp."
I'm assuming there's a query that will select this table, sort the rows by timestamp, group them in 24-hour increments and then count the number of rows in each group - telling me how many new comments I received each day.
What would that query look like? I think I can figure out the other ones if I had the first one working.
This fragment will display your results in a themed table:
$sq = 'SELECT COUNT(*) cnt, DATE(FROM_UNIXTIME(timestamp)) day '
. 'FROM {comments} c '
. 'GROUP BY 2 '
. 'ORDER BY 2 DESC';
$q = db_query($sq);
$stats = array();
while ($o = db_fetch_object($q)) {
$stats[$o->day] = array($o->day, $o->cnt);
}
return theme('table', NULL, $stats));
Using DATE(timestamp) doesn't work because comments.timestamp is in UNIX_TIMESTAMP format, whereas DATE() expects an ASCII date.
Use the date_format() function to format the dates;
select count(id) as commentCount, date_format(dateColumn, '%Y-%m-%d') as commentDate
from yourTable
group by commentDate