在特定列中按条件求和

时间:2019-12-05 07:37:49

标签: sql sql-server

我对SQL Server SUM查询有疑问。

我有2张桌子:

1)EmployeesAtt(EId,EName,统计数据)->我有一些统计数据标准(0 =延迟,1 =加班,2 =正常)

   -----------------------------
   |  EId  |  EName  |  Stats  |
   -----------------------------
   |   1   |  John   |   0     |
   |---------------------------|
   |   1   |  John   |   1     |
   |---------------------------|   
   |   1   |  John   |   0     |
   |---------------------------|
   |   2   |  Lynda  |   2     |
   -----------------------------

2)AttLogs(ID,EId,延迟,加班,正常)

从EmployeesAtt表中,我想将AttLogs专用列中的EId和统计信息相加,如下所示:

   --------------------------------------------------
   |  ID   |   EId   |   late  |  overtime | Normal |
   --------------------------------------------------
   |   0   |  John   |   2     |     1     |    0   |
   |------------------------------------------------|
   |   1   |  Lynda  |   0     |     0     |    1   |
   --------------------------------------------------

这是我到目前为止所做的:

select EA.EId, EA.EName, late = case when Stats = 0 then SUM(Stats) END, 
overtime = case when Stats = 1 then SUM(Stats) END,
normal = case when Stats = 2 then SUM(Stats) END
From EmployeesAtt EA JOIN AttLogs AL ON AL.EId = EA.EId
GROUP BY EA.EId, EA.EName, EA.Stats

但结果与我上面预期的不同。

2 个答案:

答案 0 :(得分:1)

您需要使用条件聚合,并对CASE表达式求和/计数:

SELECT
    ea.EId,
    ea.EName,
    COUNT(CASE WHEN Stats = 0 THEN 1 END) AS late, 
    COUNT(CASE WHEN Stats = 1 THEN 1 END) AS overtime, 
    COUNT(CASE WHEN Stats = 2 THEN 1 END) AS normal
FROM EmployeesAtt ea
INNER JOIN AttLogs al
    ON al.EId = ea.EId
GROUP BY
    ea.EId,
    ea.EName;

答案 1 :(得分:0)

sql服务器中最大限度地使用iif函数。

select EA.EId
    , EA.EName
    , late = sum(iif(Stats=0, 1, 0))
    , overtime = sum(iif(Stats=0, 1, 0))
    , normal = sum(iif(Stats=0, 1, 0))
From EmployeesAtt EA 
JOIN AttLogs AL ON AL.EId = EA.EId
GROUP BY EA.EId, EA.EName