选择几个表

时间:2015-11-28 21:23:05

标签: oracle oracle11g

我想从这些表中选择两种类型的代理:

CREATE TABLE AGENT(
  ID INTEGER NOT NULL,
  GROUP_ID NUMBER(38,0),
  NAME VARCHAR2(30 ),
  SERIAL_NUMBER VARCHAR2(60 ),
  STATUS VARCHAR2(30 ),
  OS VARCHAR2(60 ),
  IP_ADDRESS VARCHAR2(40 ),
  NETWORK_PORT INTEGER,
  LAST_SYNC DATE,
  DATE_AGENT_ADDED DATE,
  SYNCHRONIZATION_TIME VARCHAR2(30 ),
  DESCRIPTION CLOB
)
/

CREATE TABLE AGENT_GROUP(
  ID NUMBER(38,0) NOT NULL,
  NAME VARCHAR2(40 ) NOT NULL,
  TYPE VARCHAR2(30 ),
  DATE_ADDED DATE,
  LAST_MODIFIED DATE,
  DESCRIPTION CLOB
)
/

我使用此Oracle SQL查询仅显示活动代理:

SELECT ag.NAME AS NAME, COUNT(a.NAME) AS AA_COUNT FROM AGENT_GROUP ag, AGENT a  
WHERE ag.ID = a.GROUP_ID AND a.STATUS = 'Active' GROUP BY ag.NAME 
UNION ALL SELECT NAME, 0 FROM AGENT_GROUP WHERE ID NOT IN (SELECT GROUP_ID FROM AGENT)
ORDER BY NAME;

结果如下:

NAME                                       AA_COUNT
---------------------------------------- ----------
AgentGroup                                        1

我想得到这个结果:

GROUP_NAME        AA_COUNT  Active_Agent     AAA_COUNT  Active_Agent     AAAA_COUNT
----------------- ------ -- ---------------- ---------  ---------------- ----------  
AgentGroup        1         Agent_Name       2          Agent_Name       2

第一列应该是代理组名称。

您能否告诉我如何修改此SQL查询?

1 个答案:

答案 0 :(得分:0)

要在组内进行计数,您需要使用窗口函数count() over ( partition by )

然后为每个组选择activeblocked代理,然后全外连接它们。这是我得到的结果

    GROUP_NAME  COUNT_OF_AGENTS ACTIVE_AGENT_NAME   COUNT_OF_ACTIVE_AGENTS  BLOCKED_AGENT_NAME  COUNT_OF_BLOCKED_AGENTS
1   Group 1 3   Agent 1 2   Agent 3 1
2   Group 1 3   Agent 2 2   Agent 3 1
3   Group 2 2   Agent 4 1   Agent 5 1



insert into AGENT_GROUP(id, name) values (1,Group 1)  
insert into AGENT_GROUP(id, name) values (2,Group 2)

insert into AGENT(ID, GROUP_ID, NAME, STATUS) values (1,1,Agent 1,'Active');
insert into AGENT(ID, GROUP_ID, NAME, STATUS) values (2,1,Agent 2,'Active');
insert into AGENT(ID, GROUP_ID, NAME, STATUS) values (3,1,Agent 3,'Blocked');

insert into AGENT(ID, GROUP_ID, NAME, STATUS) values (4,2,Agent 4,'Active');
insert into AGENT(ID, GROUP_ID, NAME, STATUS) values (5,2,Agent 5,'Blocked');


SELECT distinct
  nvl(ag_a.NAME, ag_b.name) AS GROUP_NAME 
 ,count(distinct a_a.name) over (partition by ag_a.id) + count(distinct a_b.name) over (partition by ag_b.id) as count_of_agents
 ,a_a.name as active_agent_name 
 ,count(distinct a_a.name) over (partition by ag_a.id) as count_of_active_agents
 ,a_b.name as blocked_agent_name 
 ,count(distinct a_b.name) over (partition by ag_b.id) as count_of_blocked_agents 
 FROM AGENT_GROUP ag_a
   left outer join agent a_a on 
         ag_a.id = a_a.group_id  
     and a_a.STATUS = 'Active'
   full outer join AGENT_GROUP ag_b on ag_a.id = ag_b.id 
   left outer join agent a_b on 
         ag_b.id = a_b.group_id  
     and a_b.STATUS = 'Blocked'
order by 1