主要实现功能:主表记录借用的主体信息,而在jieyong_list表中有借用物品的明细记录,其中记录着2种状态“未归还”和“已归还”,现在需要筛选出表中“全部已归还”和“全部未归还”的记录,而不是哪些已归还或未归还的零散记录,是要按整体查询的。
利用CASE WHEN THEN ELSE、GROUP BY、HAVING组合使用查询。
//统计“所有未归还” select dh,count(*) AS all_nums,SUM(CASE WHEN zhuangtai = '已归还' THEN 1 ELSE 0 END) AS yiguihuan from jieyong_list where zhangtao='001' GROUP BY dh HAVING yiguihuan=0 //统计“所有已归还” select dh,count(*) AS all_nums,SUM(CASE WHEN zhuangtai = '已归还' THEN 1 ELSE 0 END) AS yiguihuan from jieyong_list where zhangtao='001' GROUP BY dh HAVING yiguihuan=all_nums //思路记录:利用CASE WHEN如果状态='已归还' 则 yiguihuan+1 SUM(CASE WHEN zhuangtai = '已归还' THEN 1 ELSE 0 END) AS yiguihuan //思路记录:group by dh单独用将dh独立分组显示,加上having则增加限定条件 GROUP BY dh HAVING yiguihuan=0
采用GROUP BY dh的结果:
采用GROUP BY dh HAVING yiguihuan=0的结果: