-1

I have a database with some data.

for example:

Time    Type
1:00    123
2:00    123
3:00    123
4:00    123
5:00    113
6:00    113
7:00    113
8:00    113
9:00    334
10:00   334
11:00   334
12:00   123

And I would like to have an output from DB something like so:

At 5:00 type changed from 123 to 113
At 9:00 type changed from 113 to 334
At 12:00 type changed from 334 to 123

I've tried that via GROUP BY, but that outputted only different values, so it was OK, but when there were same date types, it outputted only the first change, because it was grouped only into one, of course...

Could anyone help me, please?

Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
  • Possible duplicate of [MySQL - Subtracting value from previous row, group by](http://stackoverflow.com/questions/13196190/mysql-subtracting-value-from-previous-row-group-by) – Matt Apr 05 '17 at 20:03

1 Answers1

0

Don't forget to mark this answer as "solved" if this solves your problem.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
        } 

$sql = "SELECT Time, Type FROM MyTable";
$result = $conn->query($sql);

// Declare 4 variables to store time and type so you can compare to previous.
$time1 = "";
$type1 = "";
$time2 = "";
$type2 = "";

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $time2 = $row["Time"];
        $type2 = $row["Type"];
        if ($type2 == $type1) {
            $time1 = $time2;
            $type1 = $type2;
            }
        else {
            echo "At $tim2 type changed from $type1 to $type2";
            $time1 = $time2;
            $type1 = $type2;
            }
        }
    }
else {
    echo "0 results";
    }
$conn->close();
?>

You can shorten the code for the loop and write this:

    while($row = $result->fetch_assoc()) {
        $time2 = $row["Time"];
        $type2 = $row["Type"];
        if ($type2 != $type1) {
            echo "At $tim2 type changed from $type1 to $type2";
            }
        $time1 = $time2;
        $type1 = $type2;
        }

To exclude the first result when the loop starts, write this:

    while($row = $result->fetch_assoc()) {
        $time2 = $row["Time"];
        $type2 = $row["Type"];
        if ($type2 != $type1 && $type1 != "") {
            echo "At $tim2 type changed from $type1 to $type2";
            }
        $time1 = $time2;
        $type1 = $type2;
        }
Kobbe
  • 316
  • 1
  • 13