Anstatt tbl_workers beizutreten Sie könnten sich mit seiner nichtpivotierten Variante verbinden, wo position und position2 würde in der gleichen Spalte, aber in verschiedenen Zeilen stehen.
So könnte das Unpivoting aussehen:
SELECT
w.id,
w.name,
CASE x.pos WHEN 1 THEN w.position ELSE w.position2 END AS position,
w.status
FROM tbl_workers AS w
CROSS JOIN (SELECT 1 AS pos UNION ALL SELECT 2) AS x
Hier ist die gesamte Abfrage, die im Grunde Ihre ursprüngliche Abfrage ist, wobei die obige Abfrage die tbl_workers ersetzt Tabelle:
SELECT p.id,
p.position,
SUM(CASE w.Status WHEN 2 THEN 1 ELSE 0 END) AS booked,
SUM(CASE w.Status WHEN 3 THEN 1 ELSE 0 END) AS placed
FROM tbl_positions AS p
LEFT JOIN (
SELECT
w.id,
w.name,
CASE x.pos WHEN 1 THEN w.position ELSE w.position2 END AS position,
w.status
FROM tbl_workers AS w
CROSS JOIN (SELECT 1 AS pos UNION ALL SELECT 2) AS x
) AS w
ON w.position=p.id
GROUP BY p.id, p.position
AKTUALISIEREN
Dies ist ein modifiziertes Skript gemäß zusätzlicher Anfrage in den Kommentaren:
SELECT p.id,
p.position,
SUM(CASE w.Status WHEN 2 THEN 1 ELSE 0 END) AS booked,
SUM(CASE w.Status WHEN 3 THEN 1 ELSE 0 END) AS placed
FROM tbl_positions AS p
LEFT JOIN (
SELECT
w.id,
w.name,
CASE x.pos WHEN 1 THEN w.position ELSE w.position2 END AS position,
CASE w.status
WHEN 4 THEN CASE x.pos WHEN 1 THEN 3 ELSE 2 END
ELSE w.status
END AS status
FROM tbl_workers AS w
CROSS JOIN (SELECT 1 AS pos UNION ALL SELECT 2) AS x
) AS w
ON w.position=p.id
GROUP BY p.id, p.position
Die Idee ist, die 4 zu ersetzen Status im Subselect mit 3 oder 2 je nachdem, ob wir gerade position ziehen sollen oder position2 als einheitliche position . Die äußere Auswahl verwendet weiterhin die gleiche Logik wie zuvor.