SELECT
cs2.userId,
count(cs2.storeId) AS count_stores
FROM
chess_storetry AS cs2,
(SELECT
cs.storeId,
min(cs.timeStore) AS timeStore
FROM
chess_storetry AS cs,
_historystore AS h
WHERE
cs.numberTry = 0 AND h.userId=cs.userId AND h.storeId = cs.storeId AND h.finish=1
GROUP BY
storeId) AS results
WHERE
cs2.numberTry = 0 AND cs2.storeId=results.storeId AND cs2.timeStore = results.timeStore
GROUP BY userId