SQL - группировать по запросу из другого выбора по одному запросу - PullRequest
0 голосов
/ 31 января 2019

Я пытаюсь сгруппировать результаты по идентификатору, но это не работает. Я получаю повторяющиеся строки по возвращении ... Вот мой запрос:

SELECT firstTable.id     as id,
   secondTable.holder as holder

FROM (select tb3.id as id
  from table1 tb1
         inner join table2 tb2 on tb1.tb2_id = tb2.id
         inner join table3 tb3 on tb2.tb3_id = tb3.id and tb3.id
         inner join table4 tb4 on tb4.id = tb3.tb4_id and tb4.id = 1998
  group by tb3.id) as firstTable,
 (select id_holder,
         sum(temporaryTable.holder) as holder
  from (
         select (select cast(tb4.helper as integer)) as helper,
                count(distinct tb4.id)               as holder,
                tb3.id                               as id_holder
         from table1 tb1
                inner join table2 tb2 on tb1.tb2_id = tb2.id
                inner join table3 tb3 on tb2.tb3_id = tb3.id and tb3.id
                inner join table4 tb4 on tb4.id = tb3.tb4_id and tb4.id = 1998
         group by tb3.id, tb4.helper
       ) as temporaryTable
  where temporaryTable.helper between 7 and 8
  group by id_holder) as secondTable

1 Ответ

0 голосов
/ 31 января 2019

Вам необходимо условие соединения, чтобы вы не получили полный перекрестный продукт между двумя запросами.

SELECT firstTable.id as id,
       secondTable.holder as holder
FROM (
    select tb3.id as id
    from table1 tb1
    inner join table2 tb2 on tb1.tb2_id = tb2.id
    inner join table3 tb3 on tb2.tb3_id = tb3.id and tb3.id
    inner join table4 tb4 on tb4.id = tb3.tb4_id and tb4.id = 1998
    group by tb3.id) as firstTable
JOIN (
    select id_holder,
           sum(temporaryTable.holder) as holder
    from (
        select cast(tb4.helper as integer) as helper,
               count(distinct tb4.id) as holder,
               tb3.id as id_holder
        from table1 tb1
        inner join table2 tb2 on tb1.tb2_id = tb2.id
        inner join table3 tb3 on tb2.tb3_id = tb3.id and tb3.id
        inner join table4 tb4 on tb4.id = tb3.tb4_id and tb4.id = 1998
        group by tb3.id, tb4.helper
    ) as temporaryTable
    where temporaryTable.helper between 7 and 8
    group by id_holder) as secondTable
ON firstTable.id = temporaryTable.id_holder
...