您的位置:首页 > 数据库 > Oracle

oracle统计(当前层级以及所有下级组织机构登录次数总和)

2016-07-06 10:16 537 查看
有两张表,一张组织机构表(存父级与子级组织机构关系),一张登录统计表(存组织机构登录日志),表结构如下图:





因用户登录时统计登录日志只有当前组织机构的登录信息,没有被包含在父级登录信息中,而需求为统计父级登录次数时要把当前组织机构以及下属所有组织机构的登录次数加起来(选定时间段内、可以指定多个组织机构)。

====================================================================================================================================

函数(参数:组织机构ID、开始日期、结束日期):

CREATE OR REPLACE FUNCTION "getT" (orId IN VARCHAR2, ts IN VARCHAR2, te IN VARCHAR2)

RETURN NUMBER

IS

temp   NUMBER;

BEGIN

    select ti into temp from (select

    sum(case when lg.id is null then 0 else 1 end) as ti

    from

        (

                select ll.orgid from TBL_ORGM_ORG@PORTAL_TO_ASM ll start with ll.orgid=orId connect by prior ll.orgid=ll.PARENTORGID

        )ids

    left join  TBL_LOGON_VISIT lg on ids.orgid = lg.orgid

    where TO_CHAR (lg.visittime, 'yyyy-mm-dd') BETWEEN ts AND te

);

    

    RETURN (temp);

END;

====================================================================================================================================

调用函数SQL:

select mm.orgid,

(select "getT"(mm.orgid,'2016-05-31','2016-06-30') from dual) as tim

from TBL_ORGM_ORG@PORTAL_TO_ASM mm

where mm.orgid in('10010000','32500050')

====================================================================================================================================

查询结果如下图:









====================================================================================================================================

注释:如果两个表不在一个数据库里,跨库可以建立database link(以上SQL里出现的@PORTAL_TO_ASM均为跨库连接)

建立database link的SQL如下:

--Create database link

create database link PORTAL_TO_ASM       --要建立的database link名

  connect to asm  IDENTIFIED BY asm         --访问用户名、密码

  using '10.246.145.159/ipms';                        --访问路径、数据库名

====================================================================================================================================

select ll.orgid from TBL_ORGM_ORG@PORTAL_TO_ASM ll start with ll.orgid='32500050' connect by prior ll.orgid=ll.parentorgid

等价于

select ll.orgid  from TBL_ORGM_ORG@PORTAL_TO_ASM ll start with ll.parentorgid='32500050' connect by prior ll.orgid=ll.parentorgid

union

select ll.orgid from TBL_ORGM_ORG@PORTAL_TO_ASM ll where ll.orgid='32500050'

参考下图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  oracle 统计