如何在不计算第二个表中的双精度的情况下构建连接?

puruo6ea  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(313)

这个问题在这里已经有答案了

来自多个表的sql和数据(6个答案)
11个月前关门了。
我有两个表,我正试图建立一个查询,但我没有正确的结果,有人能帮我吗?
表1:

  1. code|name
  2. 74|Jhon
  3. 06|Sara
  4. 92|Fred
  5. 75|Fred
  6. 06|Sara
  7. 13|Lola

表2:

  1. code|amount|folder
  2. 06|500|1
  3. 74|135|0
  4. 13|150|0
  5. 13|100|1
  6. 92|200|1
  7. 75|250|0
  8. 06|300|1

我要按名称选择文件夹的数量和总数,以及包含0的文件夹的数量。
我做了以下查询:

  1. select table1.name,
  2. sum(table2.amount) as amount_tot,
  3. count(table2.folder) as nb_folder,
  4. sum(table2.folder) as nb_folder_ko
  5. from table1 inner join table2 on table1.code=table2.code
  6. group by name

我得到以下结果:

  1. name|amount_tot|nb_folder|nb_folder_ko
  2. Lola|250|2|1
  3. Fred|450|2|1
  4. Sara|1600|4|4
  5. Jhon|135|1|0

如您所见,关于我的源表,这是不正确的,我认为我的查询做了一些重复计算,但我不知道如何修复它,请帮助我:)

q9rjltbz

q9rjltbz1#

你得到一个多对多的连接(而不是一对多)。在联接之前应用distinct:

  1. select table1.name,
  2. sum(table2.amount) as amount_tot,
  3. count(table2.folder) as nb_folder,
  4. sum(table2.folder) as nb_folder_ko
  5. from
  6. (
  7. select distinct name, code
  8. from table1
  9. ) as table1
  10. inner join table2
  11. on table1.code=table2.code
  12. group by name

如果名称/代码组合不是唯一的,请切换到

  1. select max(name), code
  2. from table1
  3. group by code
展开查看全部

相关问题