我目前有以下查询,它返回特定员工和月份的时间表条目:
SELECT supervisors.employee,
hourscharged.project,
hourscharged.chargedescription,
hourscharged.account,
hourscharged.org,
hourscharged.entered_hrs
FROM accounting
INNER JOIN hourscharged
ON hourscharged.period_no_cd = accounting.period_no_cd
INNER JOIN supervisors
ON hourscharged.employeeid = supervisors.employeenumber
WHERE supervisors.employee = 'JOHN'
AND accounting.accountingmonth = 'FEB-13'
GROUP BY supervisors.employee,
hourscharged.project,
hourscharged.chargedescription,
hourscharged.account,
hourscharged.org,
hourscharged.entered_hrs
该查询返回 7 行,其中包含以下值
员工 | 项目 | 收费说明 | 帐户 | 组织 | ENTERED_HRS: 约翰 | 15113 | MBT升级 | 0510 | 1.1.10.5 | 2.00 约翰 | 15113 | MBT升级 | 0510 | 1.1.10.5 | 3.50 约翰 | 15113 | MBT升级 | 0510 | 1.1.30.4 | 2.00 约翰 | 15113 | MBT升级 | 0510 | 1.1.30.4 | 3.50 约翰 | 34188 | KY13科技 | 0320 | 1.1.30.4 | 1.00 约翰 | 34188 | KY13科技 | 0320 | 1.1.30.4 | 4.00 约翰 | 34188 | KY13科技 | 0320 | 1.1.30.4 | 8.00
这些是时间表条目。我想显示具有这些行总数的唯一行,即:
约翰 | 15113 | MBT升级 | 0510 | 1.1.10.5 | 5.50 约翰 | 15113 | MBT升级 | 0510 | 1.1.30.4 | 5.50 约翰 | 34188 | KY13科技 | 0320 | 1.1.30.4 | 13.00
我试过了:
SELECT supervisors.employee,
hourscharged.project,
hourscharged.chargedescription,
hourscharged.account,
hourscharged.org,
Sum(hourscharged.entered_hrs) <-- *
FROM accounting
INNER JOIN hourscharged
ON hourscharged.period_no_cd = accounting.period_no_cd
INNER JOIN supervisors
ON hourscharged.employeeid = supervisors.employeenumber
WHERE supervisors.employee = 'JOHN'
AND accounting.accountingmonth = 'FEB-13'
GROUP BY supervisors.employee,
hourscharged.project,
hourscharged.chargedescription,
hourscharged.account,
hourscharged.org,
hourscharged.entered_hrs
并得到:
约翰 | 15113 | MBT升级 | 0510 | 1.1.10.5 | 38.50 约翰 | 15113 | MBT升级 | 0510 | 1.1.30.4 | 38.50 约翰 | 34188 | KY13科技 | 0320 | 1.1.30.4 | 91.00
这很奇怪,因为以下查询(例如)
SELECT chargedescription,
Sum(entered_hrs)
FROM hourscharged
WHERE employeeid = '123456'
AND chargedescription LIKE 'KY13 S & T'
GROUP BY chargedescription
给出了正确的总小时数,即:
约翰 | 34188 | KY13科技 | 0320 | 1.1.30.4 | 70.00
我可以用 SUM 做我想做的事吗?如果是这样,请指导我。我对聚合 SUM 函数的应用进行了广泛搜索,但似乎无法将其应用于我自己的问题。我也觉得奇怪的是,在我的复杂查询中使用 SUM 而不是 ENTERED_HRS 给了我完全错误的总小时数。如果 SUM 不起作用,那会怎样?我无法理解我需要应用的原则。此查询所基于的架构可能并不理想,但它是遗留的,我需要使用它。我也在使用 SQL Server 2005。谢谢。
我的查询INNER JOIN
相当于:
SELECT supervisors.employee,
hourscharged.project,
hourscharged.chargedescription,
hourscharged.account,
hourscharged.org,
hourscharged.entered_hrs
FROM supervisors,
accounting,
hourscharged
WHERE supervisors.employee = 'JOHN'
AND hourscharged.employeeid = supervisors.employeenumber
AND accounting.accountingmonth = 'FEB-13'
AND hourscharged.period_no_cd = accounting.period_no_cd
GROUP BY supervisors.employee,
hourscharged.project,
hourscharged.chargedescription,
hourscharged.account,
hourscharged.org,
hourscharged.entered_hrs