So, this is my first question here, and I'd really appreciate if someone could help me. I currently have a Mysql database and a web app made with PHP where the users can input how much time they have used on a specific task that day.
Right now I would like to populate an HTML table with the SUM of each days activity in hours. My problem is that I can't find a way to check if the name field is unique, as the data contains many rows with the same name field, one for each day.
I have this Mysql query:
SELECT
t_email.name,
DATE_FORMAT(input_date,'%d') AS days,
SUM(time_worked) AS totalTime
FROM
t_transactions
LEFT JOIN t_email ON t_transactions.email_id >= t_email.email_id
WHERE
DATE_FORMAT(input_date,'%m') = '02'
AND DATE_FORMAT(input_date,'%Y') = '2019'
GROUP BY DATE_FORMAT(input_date,'%d')
ORDER BY t_email.name
Which returns me a table like this:
name days totalTime
james 01 5.00
james 06 2.00
jimmy 02 4.0
And so on. I'm using the below PHP:
<?php
foreach ($monthly_data_per_day as $row): ?>
<tr>
<td><?= $row['name'] ?></td>
<?php
$num_days = date('t');
for ($i = 1; $i <= $num_days; $i++) {
if ($row['days'] == $i) {
echo "<td>" . $row['totalTime'] . "</td>";
} else {
echo "<td>" . 0 . "</td>";
}
}?></tr>
<?php endforeach;?>
I'd like to have an HTML table where after each name in the database, you could see how many hours that person has done that day. So columns from 1 to how many days there are in the month.
Right now I get a row for each day, with the correct sum of time worked on just one column, as there's one row per column.
Here's a picture of what I'd like the table to look like:
A picture of the table with columns for each day of the month
There is a solution for this using conditional aggregation... that will requires you to write 31 CASE
statements, like :
SELECT
e.name,
SUM(CASE WHEN DAYOFMONTH(t.input_date) = 1 THEN t.time_worked ELSE 0 END) AS day1,
SUM(CASE WHEN DAYOFMONTH(t.input_date) = 2 THEN t.time_worked ELSE 0 END) AS day2,
SUM(CASE WHEN DAYOFMONTH(t.input_date) = 3 THEN t.time_worked ELSE 0 END) AS day3,
...
FROM
t_transactions t
LEFT JOIN t_email e ON t.email_id = e.email_id
WHERE YEAR(input_date) = 2019 AND MONTH(t.input_date) = 2
GROUP BY e.name
ORDER BY e.name
Other remarks :
I guess that you meant t.email_id = e.email_id
instead of t.email_id >= e.email_id
it will probably more efficient to use MySQL built-in date functions such as YEAR
, DAYOFMONTH
and MONTH
, which return integers, rather than manipulating formated string representations of dates
as not all of the fields in your query were aliase, I made the assumption that columns input_date
and time_worked
belong to table t_transactions
.
since we SELECT e.name
, this column needs to appear in the GROUP BY
clause ; on non-ancient versions of MySQL, this is a syntax error
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.