我有以下表格:
模式
tbl_semester_empid {id,semester_name varchar(50),start_date}
tbl_batch_empid {id,semester_id,batch_name,session_room}
tbl_associate_empid {id,associate_name,batch_id,contact,joined_date,induction_result,stream_result int}
问题查询是:显示学期明智的关联计数。
我写了3个查询:
--basic query
SELECT s.ID "Semester Id", COUNT(*) "Associate Count" FROM TBL_SEMESTER_593932 s, TBL_ASSOCIATE_593932 a, TBL_BATCH_593932 b
WHERE s.ID=b.SEMESTER_ID AND a.BATCH_ID=b.ID
GROUP BY s.ID;
--used NVL function
SELECT s.ID "Semester Id", NVL(COUNT(*),0) "Associate Count" FROM TBL_SEMESTER_593932 s, TBL_ASSOCIATE_593932 a, TBL_BATCH_593932 b
WHERE s.ID=b.SEMESTER_ID AND a.BATCH_ID=b.ID
GROUP BY s.ID;
-- used LEFT OUTER JOIN and JOIN
SELECT s.ID "Semester Id", NVL(COUNT(*),0) "Associate Count"
FROM TBL_SEMESTER_593932 s LEFT OUTER JOIN TBL_BATCH_593932 b ON s.ID=b.SEMESTER_ID
JOIN TBL_ASSOCIATE_593932 a ON a.BATCH_ID=b.ID
GROUP BY s.ID;
所有这些都显示以下输出(它显示的记录仅对应于其中至少有一名学生的学期,如果该学期不是学生,则不会显示该学期的信息):
我希望没有关联者的学期在“关联计数”列中为0。所以我尝试了两个LEFT OUTE JOIN:
SELECT s.ID "Semester Id", NVL(COUNT(*),0) "Associate Count"
FROM TBL_SEMESTER_593932 s LEFT OUTER JOIN TBL_BATCH_593932 b ON s.ID=b.SEMESTER_ID
LEFT OUTER JOIN TBL_ASSOCIATE_593932 a ON a.BATCH_ID=b.ID
GROUP BY s.ID;
但结果很奇怪:
答案 0 :(得分:1)
您是否尝试过使用CASE when
?
根据您的关联表中的数据,所有批次/学期都有记录。
所以试试这个,你的NVL与案例类似......
select s.id, s.name, CASE WHEN count(a.id) IS NULL THEN 0 ELSE count(a.id) END as ACount
from tblsem s
left join tblbatch b
on b.sid = s.id
left join tblaso a
on b.id = a.batchid
group by s.id, s.name
;
结果:
ID NAME ACOUNT
1 sem1 4
2 sem2 3
3 sem3 0
答案 1 :(得分:1)
基本上,你要做的就是使用所有可用学期的清单,然后计算每个学期的数量:
select s.ID,
s.Semester_Name,
NVL ((select count(*)
from TBL_ASSOCIATE_593932 a
join TBL_BATCH_593932 b
on a.BATCH_ID=b.ID
where s.ID=b.SEMESTER_ID
),0) as Amount
from TBL_SEMESTER_593932 s
另一种方法是加入你所有学期的名单,然后计算
select s.ID,
s.Semester_Name,
count(*) as Amount
from TBL_SEMESTER_593932 s
left join (
TBL_BATCH_593932 b
join TBL_ASSOCIATE_593932 a
on a.BATCH_ID=b.ID)
on s.ID=b.SEMESTER_ID
group by s.ID, s.Semester_Name
order by s.ID
[编辑]:根据@ Mahesha999更正了最后一个查询。