简体   繁体   中英

How to get sum of same value and different value in same row?

table 1
invno percentage cost
1 18% 18.00
1 18% 18.00
2 18% 18.00
2 28% 28.00

table 2
id percentage
1 18%
2 28%

The table 2 percentage column values should become the column headings of output.

In table 1, invno 1 has 2 entries, but the same percentage value of 18% ; invno 2 has 2 entries with different percentage values.

output

invno    percentage 18%    percentage 28%
  1           36.00             0.00
  2           18.00            28.00

So far I have written:

SELECT
    `invno`,
    SUM(CASE WHEN `percentage` = '18' THEN `percentage` ELSE NULL END) AS `percentage_18`,
    SUM(CASE WHEN `percentage` = '28' THEN `percentage` ELSE NULL END) AS `percentage_28`
FROM `table1`
GROUP BY `invno`
HAVING 18 IS NOT NULL AND 28 IS NOT NULL
ORDER BY `invno`

This is fine, but I want to get the percentages dynamically.

Over a bowl of cereal this morning, I quickly scratched out a two-step approach to generate your desired output in a dynamic fashion.

if (!$conn = new mysqli("localhost", "root","","dbname")) {
    echo "Database Connection Error"; // $conn->connect_error
} else {
    if (!$result = $conn->query("SELECT DISTINCT percentage FROM percents ORDER BY percentage")) {
        echo "Syntax Error"; // $conn->error
    } else {
        $select_columns = ['invno'];
        foreach ($result as $row) {
            $percent = (int)$row['percentage'];
            $select_columns[] = "SUM(CASE WHEN percentage = {$percent} THEN `percentage` ELSE 0 END) AS percentage_{$percent}";
        }
        if (!$result = $conn->query("SELECT " . implode(', ', $select_columns) . " FROM invoices GROUP BY invno ORDER BY invno")) {
            echo "Syntax Error"; // $conn->error
        } else {
            echo "<table border=1>";
                foreach ($result as $index => $row) {
                    if (!$index) {
                        echo '<tr><th>' , implode('</th><th>', array_keys($row)) , '</th></tr>';
                    }
                    echo '<tr><td>' , implode('</td><td>', $row) , '</td></tr>';
                }
            echo "</table>";
        }
    }
}

Effectively, I queried for unique percentage values from table2, then used those values to dynamically construct the SUM(CASE...)) expressions on table1. If this doesn't exactly work as you require on your actual project data, please supply a better/larger representation of your db data which isolates the issue so that I can update my answer.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM