SQL Server:带连接的多个计数

时间:2016-06-24 16:21:54

标签: sql-server database count

我正在编写一个查询,列出银行业务场景中特定员工所服务的客户数量。

表格的设计如下:

Table Design

以下查询产生了我需要的结果:

SELECT 
    EMPID, COUNT(EMPID) AS 'Customers Served' 
FROM 
    Financial.AccountOperations 
GROUP BY 
    EMPID;

SELECT 
    EMPID, COUNT(EMPID) AS 'Customers Served' 
FROM 
    Financial.LoanOperations
GROUP BY 
    EMPID;

Query Results

我正在尝试将查询合并为一个。我尝试过使用UNIONINTERSECTJOIN和子查询但没有成功。

有人可以帮忙吗?

所需的输出如下:

 EMPID         Customers Served  
   2                2  
   3                3  
   4               17  
   5               16  
   7                2  
   8                4  
   9                8  
  10                5  
  12                1  
  15                1  

2 个答案:

答案 0 :(得分:2)

你试过这个:

SELECT EMPID,COUNT(EMPID) AS 'Customers Served' 
FROM Financial.AccountOperations
GROUP BY EMPID

UNION

SELECT EMPID,COUNT(EMPID) AS 'Customers Served'
FROM Financial.LoanOperations 
GROUP BY EMPID;

我想我会这样做

SELECT 'Account' AS Source, EMPID,COUNT(EMPID) AS 'Customers Served' 
FROM Financial.AccountOperations
GROUP BY EMPID

UNION ALL

SELECT 'Loan' AS Source, EMPID,COUNT(EMPID) AS 'Customers Served'
FROM Financial.LoanOperations 
GROUP BY EMPID;

答案 1 :(得分:2)

我认为@Hogan有它 - 再多花一步:

SELECT EMPID, Sum([Customers Served]) AS NumServed FROM
(SELECT EMPID,COUNT(EMPID) AS 'Customers Served' 
FROM Financial.AccountOperations
GROUP BY EMPID
UNION
SELECT EMPID,COUNT(EMPID) AS 'Customers Served'
FROM Financial.LoanOperations 
GROUP BY EMPID)
GROUP BY EMPID