|
SELECT c.id_user as id, c.phone, c.surname, c.name, c.patronymic, IFNULL(c.sum11,0)+IFNULL(d.sum22,0) as sum, c.current_cashback
FROM
(
SELECT a.id_user, a.phone, a.surname, a.name, a.patronymic, IFNULL(a.sum1,0)+IFNULL(b.sum2,0) as sum11, a.current_cashback FROM
(
SELECT a1.id_user, a2.phone, a2.surname, a2.name, a2.patronymic, sum(a1.cashback) as sum1, a2.cashback as current_cashback FROM company_cashback a1, company_user a2 WHERE a1.id_user=a2.id AND a1.data>=1627758000 AND a1.data<1630436400 AND a1.cashback>0 AND (a1.id_category=1 OR a1.id_category=2) GROUP BY a1.id_user
) a
LEFT JOIN
(
SELECT id_user, sum(cashback) as sum2 FROM company_cashback WHERE data>=1633028400 AND data<1635706800 AND cashback>0 AND (id_category=3 OR id_category=4 OR id_category=5 OR id_category=7) GROUP BY id_user
) b
ON a.id_user=b.id_user
UNION
SELECT a.id_user, a.phone, a.surname, a.name, a.patronymic, IFNULL(a.sum1,0)+IFNULL(b.sum2,0) as sum11, a.current_cashback FROM
(
SELECT a1.id_user, a2.phone, a2.surname, a2.name, a2.patronymic, sum(a1.cashback) as sum1, a2.cashback as current_cashback FROM barbarra_cashback a1, company_user a2 WHERE a1.id_user=a2.id AND a1.data>=1627758000 AND a1.data<1630436400 AND a1.cashback>0 AND (a1.id_category=1 OR a1.id_category=2) GROUP BY a1.id_user
) a
RIGHT JOIN
(
SELECT id_user, sum(cashback) as sum2 FROM company_cashback WHERE data>=1633028400 AND data<1635706800 AND cashback>0 AND (id_category=3 OR id_category=4 OR id_category=5 OR id_category=7) GROUP BY id_user
) b
ON a.id_user=b.id_user
) c
LEFT JOIN (SELECT id_user, sum(cashback) as sum22 FROM company_cashback WHERE data>=1630436400 AND data<1635706800 AND cashback<0 GROUP BY id_user) d
ON c.id_user=d.id_user
Да, и это всё один sql-запрос в МySQL! :))
| |