2016-04-12 14 views
9

mi chiedevo se qualcuno può aiutare con questoquery MySQL con subsort per tipo

ho le seguenti tabelle

user_ids { 
    uUID 
    name 
} 

types { 
    tUID 
    name 
} 

activity { 
    aUID 
    user_id 
    type_id 
    date 
} 

modo che gli utenti conterrebbe

uUID name 
1  Bob 
2  Mark 
3  Peter 

tipi sarebbe

tUID name 
1  Baseball 
2  Football 
3  Cricket 

activit y sarebbe

aUID user_id type_id date 
1   1   2 
2   1   2 
3   1   3 
4   2   1 
5   2   3 
6   2   1 
7   3   3 
8   3   3 
9   3   3 

ora quello che vorrei ottenere è la seguente tabella posteriore

Name Type  Count of type 
Bob Baseball 0 
Bob Football 2 
Bob Cricket 1 
Mark Baseball 2 
Mark Football 0 
Mark Cricket 1 
Peter Baseball 0 
Peter Football 0 
Peter Cricket 3 

posso fare questo con un'unica query di per utente id ma vorrei sapere se c'è un modo per fai questo con una singola query.

Grazie

Martin

risposta

4

Prova come questo

Con lo zero

SELECT X.Name ,X.Type, 
SUM(CASE WHEN A.user_id IS NULL THEN 0 ELSE 1 END) as `Count of type` 
FROM 
(
    SELECT T.Name AS Type,U.name AS NAME,U.uUID,T.tuid FROM types T,user_ids U 
)X LEFT JOIN activity A ON A.type_id = X.tuid AND A.user_id =X.uUID 
GROUP BY X.Name ,X.Type 
ORDER BY X.Name ,X.Type 

Senza zero

SELECT U.name AS Name, 
     T.name AS Type, 
     SUM(CASE WHEN A.user_id IS NULL THEN 0 ELSE 1 END) as `Count of type` 
FROM types T 
LEFT JOIN activity a on T.tuid=A.type_id 
JOIN user_ids U on A.user_id = U.uUID 
GROUP BY U.name, T.name 
+1

Grazie, ha funzionato alla grande. – Martin

+0

l'istruzione with zero non sembra restituire 0 se l'utente non ha eseguito alcuna attività o ha fatto solo 1 EG Peter Cricket 3 ma nient'altro – Martin

+0

No tornerà o utente ha fatto qualche attività o no –

0

Una soluzione sta usando CROSS JOIN di users e types, poi un LEFT JOIN con activity.

select u.name as Name, t.name as Type, COUNT(a.aUID) as `Count of type` 
from users u CROSS JOIN type t 
    LEFT JOIN activity a ON a.user_id = u.uUID AND a.type_id = t.tUID 
2

Devi solo a sinistra unirsi tipo di attività e di tabelle e di gruppo per utente e il tipo:

select u.name as Name, t.name as Type, COUNT(a.user_id) as `Count of type` 
from type t 
left join activity a on t.tuid=a.type_id 
left join users u on a.user_id = u.uUID 
group by u.name, t.name