两个相似子查询之间的sql连接

标签 sql db2

我是 SQL 初学者。我有两个表,一个是student_records,另一个是student_fees表,其中存在折扣费用(fee_type_code=2)和常规费用(fee_type_code=1)学生的记录。费用类型的代码是fee_type_code。由于系统存在错误,一些学生同时获得了两种费用类型。我想获取所有的错误记录。首先,我有两个查询可以单独正常工作,但我尝试将它们合并到一个查询中,然后在临时表上创建联接:

select 
student_id, fee_type_code 
from
      ((select * from student_records r, student_fees f 
        where s.student_id=f.student_id and fee_type_code=1) A 
        inner join 
       (select * from student_records r, student_fees f 
        where       
        s.student_id=f.student_id and fee_type_code=2) B 
       on A.student_id=B.student_id);

对于给您带来的任何不便,或者如果这个问题太天真,我深表歉意,但我陷入了困境。我收到的错误是“对student_id的引用不明确...”

最佳答案

如果您的目标是获取具有两种费用类型的学生列表,那么您可以使用 group byhaving 来代替:

select sr.student_id
from student_records sr
join student_fees sf on sr.student_id = sf.student_id
where sf.fee_type_code in (1,2)
group by sr.student_id
having count(distinct sf.fee_type_code) = 2

关于两个相似子查询之间的sql连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34359821/

相关文章:

hibernate - 如何使用 JPA Criteria Api 使用文字参数调用 db2 数据库函数?

db2 查询从另一个表插入

mysql - 如何编写一个 SQL 补丁,从表 A 中获取值并将其作为行插入到表 B 中?

php - 计数字符并获取在 Php 或 SQL 中出现的百分比

grails - 如何让 Grails 将我的 String 字段映射到 Clob?

sql - Cognos Report Studio 版本 10.2.1 中格式化日期提示出现问题

sql - Hibernate等于 "select 1 from DUAL"是什么?

mysql - SQL 到 HQL 查询 Grails

php - 这个 Mongo 查询和这个 SQL 查询一样吗?我是否正确地考虑了 Mongo?

sql - DB2 SQL 更新表值