I created an extra table to define which category the values were in
mysql> select * from catval;
+-----+------+
| val | cat |
+-----+------+
| 1 | 4 |
| 2 | 4 |
| 3 | 4 |
| 4 | 4 |
| 5 | 3 |
| 6 | 3 |
| 7 | 2 |
| 8 | 2 |
| 9 | 1 |
| 10 | 1 |
+-----+------+
then
$sql = "SELECT a.cat as cata
, b.cat as catb
FROM datatb d
JOIN catval a ON d.grpa = a.val
JOIN catval b ON d.grpb = b.val
";
$result = $db->query($sql);
//categories
$cat = [
4 => ['name'=>'1:4', 'recs'=>[]],
3 => ['name'=>'5:6', 'recs'=>[]],
2 => ['name'=>'7:8', 'recs'=>[]],
1 => ['name'=>'9:10','recs'=>[]]
];
$n = 0;
while ($row = $result->fetch_assoc()) {
$cat[$row['cata']]['recs'][$n][] = $row['cata'];
$cat[$row['catb']]['recs'][$n][] = $row['catb'];
$n++;
}
// the output
echo "<table border='1' style='width:500px; border-collapse:collapse;'>";
foreach ($cat as $c) {
echo "<tr><th>{$c['name']}</th>";
for ($i=0; $i<$n; $i++) {
echo '<td style="text-align:center;">' . (isset($c['recs'][$i]) ? join(',', $c['recs'][$i]) : '–') . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";