I have two tables, budget, and transaction like below:
Budget
|id | acc_code | desc |
|:-:|----------|---------|
|1 |A.IV.1 |Car |
|2 |A.X.3 |Bike |
|3 |B.I.1 |Airplane |
Transaction
|id | acc_code | price | transac_date |
|:-:|----------|-------|--------------|
|1 |A.IV.1 |200 | 2021-07-01 |
|2 |A.IV.1 |300 | 2021-07-02 |
|3 |A.X.3 |50 | 2021-07-06 |
|4 |A.IV.1 |250 | 2021-07-06 |
|5 |A.X.3 |75 | 2021-07-12 |
|6 |B.I.1 |4500 | 2021-07-12 |
I need to get query result table like below:
|id | acc_code | desc | week 1 | week2 | week 3 | week 4 | week 5 | total of month |
|:-:|----------|---------|--------|-------|--------|--------|--------|-------|
|1 |A.IV.1 |Car |500 | | | | | 500 |
|2 |A.X.3 |Bike | | 50 | 75 | | | 125 |
|3 |B.I.1 |Airplane | | | 4500 | | | 4500 |
What I have done so far is as follows:
// Create connection
<?
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "
SELECT
budget.acc_code,
budget.desc AS description,
COALESCE(SUM(transaction.price), 0) AS total
FROM
budget
LEFT JOIN
transaction
ON budget.acc_code = transaction.acc_code
GROUP BY
budget.desc
";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
?>
<table>
<thead style="background-color: #33DFFF;" >
<tr class="info">
<th>Num</th>
<th>Acc_code</th>
<th>Desc</th>
<th>Total of month</th>
</tr>
</thead>
<tbody>
<?php
$check = mysqli_num_rows($query);
if($check > 1)
{
$num=1;
while($data = mysqli_fetch_array($query))
{
?>
<tr>
<td><?php echo $num; ?></td>
<td><?php echo $data['acc_code']; ?></td>
<td><?php echo $data['description']; ?></td>
<td><?php echo $data['total']; ?></td>
</tr>
<?php
$num++;
}
}
?>
</tbody>
</table>
<?
mysqli_close($connect);
?>
with the following results:
|num | acc_code | desc | total of month |
|:-:|----------|---------|----------------|
|1 |A.IV.1 |Car |500 |
|2 |A.X.3 |Bike |125 |
|3 |B.I.1 |Airplane |4500 |
The problem is how to parse the data into weekly and add weekly columns. My experience in doing Join Tables is actually still lacking.