Struggling with MySQL query.. time to ask for help. I am trying to get sub totals for amount of time, problem is that I can't get the other columns to show the way I want. Coding with PHP.
Plus the table values, there is also hidden ID value that is different for every row.
Doing query as:
SELECT id, date, project, SUM(duration) AS duration FROM mytable GROUP BY date desc, id with rollup"
I get it right, but I want to get rid of the project name and make the column show like "total duration:" So I don't want to make subtotal for project, just for the date. but I want to get rid of project name in total row.
Thanks in advance.
I put an example in phpize :
To the example, a table creation:
create table mytable(id int, date datetime, project varchar(255), Duration int);
insert into mytable values(1, "2022-01-30", "Project 1", 3),
(2, "2022-01-30", "Project 1", 2),
(3, "2022-01-30", "Project 2", 4),
(4, "2022-01-29", "Project 3", 4),
(5, "2022-01-28", "Project 3", 3),
(6, "2022-01-28", "Project 3", 2);
In php, the rows loop sum a variable and, on each date change, it inserts one line with a subtotal:
<?php
use Carbon\Carbon;
$now = Carbon::now()->format('d/m/Y');
printf("Today is %s\nCurrent PHP version: %s \n\n", $now, phpversion());
$query = "SELECT VERSION() as version;";
// Select using Laravel
$version = $db::select($db::raw("SELECT VERSION() as version;"));
printf('DB version (Laravel Query Builder): %s ' . PHP_EOL, $version[0]->version);
$sql = "SELECT id, date, project, duration FROM mytable order by date desc";
$result = $mysqli->query($sql);
$last_date = null;
$subtotal = 0;
$total = 0;
if ($result->num_rows > 0) {
printf("Date Project Duration\n");
while($row = $result->fetch_assoc()) {
if ($last_date == null){
$last_date = $row["date"];
}
if( $last_date != $row["date"] )
{
printf("------------------------------------- \n");
printf("%s Total Hours %d Hours \n", $last_date, $subtotal);
printf("------------------------------------- \n");
$last_date = $row["date"];
$subtotal = 0;
}
printf( "%s %s %d Hours \n",
$row["date"],
$row["project"],
$row["duration"]
);
$subtotal += $row["duration"];
$total += $row["duration"];
}
printf("------------------------------------- \n");
printf("%s Total Hours %d Hours \n", $last_date, $subtotal);
printf(" Total Hours %d Hours \n", $total);
printf("------------------------------------- \n");
} else {
echo "0 results";
}
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.