I dag laver jeg en i PHP loop på SELECT FROM Tabel_A Inde i det loop laver jeg 2 select: SELECT SUM(Tal) AS Tal FROM Tabel_B WHERE Type = 'P' && A_ID = [Tabel_A.ID] GROUP BY A_ID
SELECT SUM(Tal) AS Tal FROM Tabel_B WHERE Type = 'M' && A_ID = [Tabel_A.ID] GROUP BY A_ID
Ville gerne kunne lave det om til et SQL kald ala:
SELECT Tabel_B_P.Tal AS M_Tal, Tabel_B_M.Tal AS M_Tal FROM Tabel_A LEFT JOIN (SELECT SUM(Tal) AS Tal FROM Tabel_B WHERE Type = 'P' && A_ID = [Tabel_A.ID] GROUP BY A_ID) AS Tabel_B_P LEFT JOIN (SELECT SUM(Tal) AS Tal FROM Tabel_B WHERE Type = 'M' && A_ID = [Tabel_A.ID] GROUP BY A_ID) AS Tabel_B_M
Har jeg forstået det rigtigt, så kan du bruge et pas sub-selects.
SELECT A_id,Bruger_ID, (SELECT SUM(Tal) AS Tal FROM Tabel_B AS B WHERE Type = 'P' AND A.A_ID = B.A_ID) AS sum_P, (SELECT SUM(Tal) AS Tal FROM Tabel_B AS B WHERE Type = 'M' AND A.A_ID = B.A_ID) AS sum_M FROM Tabel_A AS A
Det giver på de data du opgiver her
1 1 8 2 2 2 NULL NULL 3 4 NULL NULL 4 5 NULL NULL
Synes godt om
Ny brugerNybegynder
Din løsning...
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.