mysql - 在同一个表上使用不同的 group By 子句连接 2 个查询的结果

标签 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;

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

最佳答案

每个查询都是一个“ View ”,因此您可以直接加入它们。由于您在两个查询中查询同一个表而不进行过滤(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

关于mysql - 在同一个表上使用不同的 group By 子句连接 2 个查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32791387/

相关文章:

mysql - 将数据库中字符串中的所有字符替换为其他字符?

php - 使用输入更新 phpmyadmin 中的表

sql - 连接 varchar 时的顺序。没有按预期工作

MySQL 5.0 报告 "concat does not exist"

php - 如何从 MySQL 中获取 PHP 对象

php - fatal error : call to undefined excuteQuery() processmaker at class. pmScript.php(208)

mysql - 这个mysql存储过程有什么问题?

sql - PostgreSQL - 消除类似的行,但仅限于某些值

mysql - 一起使用三个表的 SQL 查询没有返回正确的结果?

php - 对来自 MySQL 的显示数据进行分组