在同一个表上使用不同的groupByclauses对2个查询的结果进行联接

时间:2015-09-25 22:13:56

标签: mysql sql

我有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;

这些查询中的每一个都返回不同的结果计数(115和125分别基于group by子句) 我必须加入两个结果,以便我拥有所有字段和4个计数(1个来自第1个,3个来自另一个)。 如何使用SQL连接或使用Java程序将单独的查询结果操作为1输出csv。

1 个答案:

答案 0 :(得分:0)

每个查询都是“视图”,因此您可以加入它们。由于您在没有过滤(where子句)的情况下查询两个查询中的同一个表,因此内连接是好的:

python manage.py makemigrations
python manage.py migrate