简体   繁体   English

在同一个表上查询2个具有不同groupByclauses的查询的结果

[英]joing results of 2 queries with different groupByclauses on same table

I have 2 queries as shown below, 我有2个查询,如下所示,

query1 = select department as 'Department_name', firstname as 'FirstName', lastname as 'LastName', manager as 'Manager', 
title as 'Title', firstofficer as 'First_Officer', email as 'Email', resourceName as 'Resource Name', 
entitlementName as 'Ent Name', concat(resourcename, entitlementname) AS 'Entitlements', count(distinct uid) 
as 'Total_Common' from outlier_report or1 
group by department, concat(resourcename, entitlementname) 


query2 = select department as 'Department_name', 
count(distinct uid) AS 'Total count of user',
count(distinct resourcename) AS 'Total resource count', 
count(distinct concat(resourcename,entitlementname)) as 'Total  Ent Count' 
from outlier_report or2 group by department;

Each of these queries returns different count of results (115 and 125 respectively based on the group by clause) I have to join the two results so that i have all the fields and 4 counts (1 from 1st and 3 from the other). 这些查询中的每个查询都返回不同的结果计数(分别基于group by子句分别为115和125),我必须将这两个结果联接在一起,这样我才能拥有所有字段和4个计数(第一个为1,另一个为3)。 How can I do this either using SQL join or using a Java Program to manipulate the separate query results into 1 output csv. 如何使用SQL联接或Java程序将单独的查询结果处理为1个输出CSV来实现。

Each query is a "view", so you can just join them. 每个查询都是一个“视图”,因此您可以将它们加入。 Since you're querying the same table in both queries without filtering (where-clause), an inner join is good: 由于您要在两个查询中查询同一表而不进行过滤(where子句),因此内部联接是好的:

select a.department, a.AA, a.BB, b.CC, b.DD
  from ( select department, AA, BB
           from outlier_report
          group by department, concat(resourcename, entitlementname)
       ) a
  join ( select department, CC, DD
           from outlier_report
          group by department
       ) b on a.department = b.department

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM