首页 > 解决方案 > 当 Duration_Hours 是另一个数据库表的 LEFT JOIN 时,如何求和?

问题描述

我想生成一份报告,总结每位员工的总工作时间。

下面是我的 SQL 查询

SELECT WO_MaidName
      ,Maid_Name AS WO_selectMaidName
      ,Appointment_Duration
      ,Duration_Hours AS Appointment_selectDuration
FROM Appointments A
    LEFT JOIN Maid
        ON Maid_ID = WO_MaidName
    LEFT JOIN Duration
        ON Duration_ID = Appointment_Duration 
WHERE DATEPART(m, Appointment_DateTime) = DATEPART(m, DATEADD(m, -1, getdate()))
    AND DATEPART(yyyy, Appointment_DateTime) = DATEPART(yyyy, DATEADD(m, -1, getdate())) 
    AND (A.IsDelete = 0
        OR A.IsDelete IS NULL
        )
ORDER BY Appointment_ID DESC

输出如下,仅显示工作时间,不添加这两个值

当它是另一个数据库表时,如何SUM让报告列出每个员工的总工作时间?Duration_HoursLEFT JOIN


编辑:我试过这个查询,但给了我这个:

'列 'Maid.Maid_Name' 在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

SELECT WO_MaidName
      ,Maid_Name AS WO_selectMaidName
      ,Appointment_Duration
      ,SUM(Duration_Hours) AS Appointment_selectDuration
FROM Appointments A
    LEFT JOIN Maid
        ON Maid_ID = WO_MaidName
    LEFT JOIN Duration
        ON Duration_ID = Appointment_Duration 
WHERE DATEPART(m, Appointment_DateTime) = DATEPART(m, DATEADD(m, -1, getdate()))
    AND DATEPART(yyyy, Appointment_DateTime) = DATEPART(yyyy, DATEADD(m, -1, getdate())) 
    AND (A.IsDelete = 0
        OR A.IsDelete IS NULL
        )
GROUP BY WO_MaidName
ORDER BY Appointment_ID DESC

如何解决这个问题?

标签: sql-server

解决方案


您得到的错误是告诉您该怎么做:

'Column 'Maid.Maid_Name' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。'

select查询中执行聚合的所有列都需要聚合或在group by. 您需要将Maid.Maid_Name和添加Appointment_Duration到您的group by.


推荐阅读