D
D
Denis Ruchiev2016-12-29 19:34:43
MySQL
Denis Ruchiev, 2016-12-29 19:34:43

How does sum work with two JOINs?

such a query...
you need to calculate the amount of rate with different types from the same table

SELECT z.id,
count(r1.id) acount, sum(r1.rate) asum,
count(r2.id) ccount, sum(r2.rate) csum
FROM (zav z)
LEFT JOIN rating r1 ON z.id = r1.id AND r1.type = 'a'
LEFT JOIN rating r2 ON z.id = r2.id AND r2.type = 'c'
WHERE z.city =  'spb' AND z.closedzav =  '0'
GROUP BY z.id

with one join, everything works as it should, but with two joins, count and sum sum up all the values, and not separately r1 and r2, what to do?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arman, 2016-12-29
@Arik

GROUP BY (IF(r1.type = 'a', 'a', 'c')), z.id

R
Rsa97, 2016-12-29
@Rsa97

Делайте JOIN с готовыми выборками из таблиц

SELECT `z`.`id`,
       `ra`.`count` AS `acount`, `ra`.`rate` AS `asum`,
       `rc`.`count` AS `ccount`, `rc`.`rate` AS `csum`
  FROM `zav` AS `z`
  LEFT JOIN (
    SELECT COUNT(*) AS `count`, sum(`rate`) AS `rate`
      FROM `rating` 
      WHERE `type` = 'a'
      GROUP BY `id`
  ) AS `ra` ON `ra`.`id` = `z`.`id`
  LEFT JOIN (
    SELECT COUNT(*) AS `count`, sum(`rate`) AS `rate`
      FROM `rating` 
      WHERE `type` = 'c'
      GROUP BY `id`
  ) AS `rc` ON `rc`.`id` = `z`.`id`
  WHERE `z`.`city` =  'spb' AND `z`.`closedzav` =  '0'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question