SELECT d.name, d.created, SUM(q1.payout) AS psum, COUNT(q2.uid) AS cnt
FROM client d
LEFT JOIN
client q1
ON q1.uid = d.uid
LEFT JOIN
client q2
ON q2.uid = d.uid
AND q2.winning =1
GROUP BY
d.name, d.created
ORDER BY
cnt DESC
LIMIT 0, 10
Если uid
является PRIMARY KEY
, вы можете переписать его следующим образом:
SELECT d.name, d.created, SUM(payout) AS psum, COUNT(IF(winning = 1, uid, NULL)) AS cnt
FROM client d
GROUP BY
d.name, d.created
ORDER BY
cnt DESC
LIMIT 0, 10