oracle - 如何写sql语句完成如下的统计查询功能?
本文介绍了oracle - 如何写sql语句完成如下的统计查询功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
描述:java ssh 生成报表!
数据库表的结构如下:
要获得的数据报表如下:
要求:
默认查询所有
可以选择条件,部门,时间范围,状态,类别,姓名,一个条件或者多个
当有类别,状态条件时,比如查询A类的,那么B,C两类都显示为零。
附上我自己的实现:(没有加ID字段)
select t4.name name,
nvl((select count(*) from apply_info t1
where (t1.curr_status='1') and t1.category='A'
and t1.Name=t4.Name group by Name),0)
as A1,
nvl((select count(*) from apply_info t2
where (t1.curr_status='2') and t2.category='A'
and t2.Name=t4.Name group by Name),0)
as A2,
nvl((select count(*) from apply_info t1
where (t1.curr_status='1') and t1.category='B'
and t1.Name=t4.Name group by Name),0)
as B1,
nvl((select count(*) from apply_info t2
where (t1.curr_status='2') and t2.category='B'
and t2.Name=t4.Name group by Name),0)
as B2,
nvl((select count(*) from apply_info t1
where (t1.curr_status='1') and t1.category='C'
and t1.Name=t4.Name group by Name),0)
as C1,
nvl((select count(*) from apply_info t2
where (t1.curr_status='2') and t2.category='C'
and t2.Name=t4.Name group by Name),0)
as C2
from apply_info t4 where 1=1
group by Name;
各个统计和是我查询以后另外计算的,不是直接查询出来的,因为觉得加上查询和这些语句又会长很多。
到这里我就觉得查询语句太复杂了,写这么长而且大量的重复。
并且如果加上查询条件,又会涉及很复杂的拼接操作,比如当我查询某一部门,需要在最后的t4以及统计子查询加上条件;选择时间范围条件就只需要在每个统计子查询加上条件(类别,状态,也是如此);还有各种条件的组合。
所以有没有什么好的解决方案,更好的sql设计不要那么长,在动态的条件选择下有没有好的字符串的操作方案?
解决方案
这个问题的复杂性主要来自于混淆了查询结果的内容和呈现形式。从查询结果的内容看,其实就是count(*) group by 姓名, 类别, 状态
。但是在呈现形式上需要最后把类别横向展示。
呈现形式并非SQL长项。用SQL解决呈现形式问题往往导致复杂、不自然的语句。建议用其它工具展示。
这篇关于oracle - 如何写sql语句完成如下的统计查询功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文