I stedet for at deltage i tbl_workers
du kan slutte dig til dens ikke-pivoterede variant hvor position
og position2
ville være i samme kolonne, men i forskellige rækker.
Sådan kan unpivoting se ud:
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
Her er hele forespørgslen, som dybest set er din oprindelige forespørgsel, hvor ovenstående forespørgsel erstatter tbl_workers
tabel:
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
OPDATERING
Dette er et ændret script i henhold til yderligere anmodning i kommentarer:
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
Ideen er at erstatte 4
status i undervalget med 3
eller 2
afhængig af om vi i øjeblikket skal trække position
eller position2
som den forenede position
. Det ydre udvalg bliver ved med at bruge den samme logik som før.