如何将两个表与组值结合起来?
我的查询:
SELECT
employee.employee_name,
count(employee.employee_name) as count,
sum(table1.position) as totalshares
FROM
erom_kmch.table1
LEFT OUTER JOIN
erom.employee
ON employee.bene_type_table1=table1.bene_type
AND employee.bene_stype_table1=table1.bene_stype
WHERE
table1.date = '2016-04-15'
group by
employee.employee_name
UNION
SELECT
employee.employee_name,
count(employee.employee_name) as count,
sum(table2.shares) as totalshares
FROM
erom_kmch.table2
LEFT OUTER JOIN
erom.employee
ON employee.type_table2=table2.type
AND employee.bo_substat_table2=table2.bo_substat
WHERE
table2.date = '2016-04-15'
group by
employee.employee_name
返回:
employee_name count totalshares
NULL 0 0 21967
Clearing Member 9 9 1386
devloper-php 4 4 1984
devloper-.net 46 46 410713
devloper-.android 2
NULL 4056461 0 117154
devloper-.C#php 2 5 31618309
devloper-.net
Resident Individual 939 25 361020 22762
但我需要这样的输出:
employee_name count totalshares
NULL 0 139121
Clearing Member 15 5355
devloper-php 9 2293
devloper-.net 46 433475
devloper-.android 2 4056461
devloper-.C# 2 31618
Resident Individual 3668 2662925
Individual- Director 1 100
我正在加入并联合两个表,我需要对两个表的值进行分组。我得到两个输出,我需要两个表的总和和计数作为一个输出。
答案 0 :(得分:0)
您应该使用子查询:
SELECT
[YourField]
, [YourAggregate]
FROM
(SELECT
table1.holder
, table1.bene_type
, table1.bene_stype
, employee.employee_name
, COUNT(employee.employee_name) AS [count]
, SUM(table1.position) AS totalshares
FROM
erom_kmch.table1
LEFT OUTER JOIN
erom.employee
ON employee.bene_type_table1=table1.bene_type AND employee.bene_stype_table1=table1.bene_stype
WHERE
table1.date = '2016-04-15'
GROUP BY
employee.employee_name
UNION
SELECT
table2.cust_name
, table2.type
, table2.bo_substat
, employee.employee_name
, COUNT(employee.employee_name) as [count]
, SUM(table2.shares) as totalshares
FROM
erom_kmch.table2
LEFT OUTER JOIN
erom.employee
ON employee.type_table2=table2.type AND employee.bo_substat_table2=table2.bo_substat
WHERE
table2.date = '2016-04-15'
GROUP BY employee.employee_name
) AS A
GROUP BY
[YourField]
注意:您还应该使查询易于阅读。