表1
invno百分比费用
1 18%18.00
1 18%18.00
2 18%18.00
2 28%28.00
表2
id百分比
1 18%
2 28%
表2 percentage
的列值应成为输出的列标题。
在表1中,invno
1有2个条目,但是18%
的百分比值相同; invno
2有2个具有不同百分比值的条目。
输出
invno percentage 18% percentage 28%
1 36.00 0.00
2 18.00 28.00
到目前为止,我已经写过:
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`
这很好,但是我想动态获取百分比。
答案 0 :(得分:0)
今天早上,我吃了一碗麦片粥,迅速采用了两步法,以动态方式生成所需的输出。
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>";
}
}
}
有效地,我从table2中查询唯一的百分比值,然后使用这些值在table1上动态构造SUM(CASE...))
表达式。如果这不能完全满足您对实际项目数据的要求,请提供更好/更大的数据库数据表示形式,以隔离问题,以便我更新答案。