SQL-按查询分组的不同选择同一查询

时间:2019-01-31 00:15:38

标签: sql postgresql select group-by

我正在尝试按ID对结果进行分组,但无法正常工作,我在返回时仍会得到重复的行... 这是我的查询:

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 :(得分:2)

您需要一个连接条件,以便在两个查询之间不会得到完整的叉积。

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