我一直在与同行进行查询,并且一直在回转一些不寻常的数字。该查询是生产力报告。我正在尝试为特定最终用户计算所有可计费单位,将该总计与单个预期值进行比较,然后计算1周内这两个数字之间的差异。以下是我们迄今为止提出的建议:
SELECT
Employees.emp_id,
Employees.last_name+', '+Employees.first_name as staff_name,
SUM(VisitQuery.billed_value)/60 AS billed_value,
SUM(StandardQuery.num8) as expected_value
FROM
Employees
INNER JOIN
(
SELECT
ClientVisit.duration AS billed_value,
ClientVisit.emp_id,
ClientVisit.client_id
FROM
ClientVisit
WHERE
ClientVisit.non_billable = 0 AND
ClientVisit.rev_timeout >= @param1 AND
ClientVisit.rev_timeout <= @param2
) VisitQuery
ON VisitQuery.emp_id = Employees.emp_id
INNER JOIN
(
SELECT DISTINCT
CaseloadQuery.emp_id,
ClientsExt.num8
FROM
(
SELECT
ClientVisit.duration AS billed_value,
ClientVisit.emp_id,
ClientVisit.client_id
FROM
ClientVisit
WHERE
ClientVisit.non_billable = 0 AND
ClientVisit.rev_timeout >= @param1 AND
ClientVisit.rev_timeout <= @param2
) CaseloadQuery
INNER JOIN ClientsExt
ON CaseloadQuery.client_id = ClientsExt.client_id
) StandardQuery
ON Employees.emp_id = StandardQuery.emp_id
GROUP BY
Employees.emp_id,
Employees.last_name+', '+Employees.first_name`enter code here`
回报看起来像这样:
emp_id staff_name billed_value expected_value
X X 74 231
XX XX 108 279
XXX XXX 19 72
有没有人有任何想法?本周40小时的预期价值应该不高。
答案 0 :(得分:0)
在表ClientVisit
中,同一个员工(emp_id
)是否有多行可以导致多个client_id值?如果答案是肯定的,那么我认为您还应该在GROUP BY
client_id
下面我尝试重写您的查询(注意标有“添加”和“删除”的行。)
免责声明:我没有实际的数据库表来测试我的查询,所以它可能有语法和语义错误
SELECT
Employees.emp_id,
StandardQuery.client_id, -- add
Employees.last_name+', '+Employees.first_name as staff_name,
SUM(VisitQuery.billed_value)/60 AS billed_value,
SUM(StandardQuery.num8) as expected_value
FROM
Employees
INNER JOIN
(
SELECT
ClientVisit.duration AS billed_value,
ClientVisit.emp_id,
ClientVisit.client_id
FROM
ClientVisit
WHERE
ClientVisit.non_billable = 0 AND
ClientVisit.rev_timeout >= @param1 AND
ClientVisit.rev_timeout <= @param2
) VisitQuery
ON VisitQuery.emp_id = Employees.emp_id
INNER JOIN
(
SELECT DISTINCT
CaseloadQuery.emp_id,
ClientsExt.num8,
ClientsExt.client_id -- add
FROM
(
SELECT
-- ClientVisit.duration AS billed_value, -- delete
ClientVisit.emp_id,
ClientVisit.client_id
FROM
ClientVisit
WHERE
ClientVisit.non_billable = 0 AND
ClientVisit.rev_timeout >= @param1 AND
ClientVisit.rev_timeout <= @param2
)CaseloadQuery
INNER JOIN ClientsExt
ON CaseloadQuery.client_id = ClientsExt.client_id
)StandardQuery
ON Employees.emp_id = StandardQuery.emp_id
GROUP BY
Employees.emp_id,
-- Employees.last_name+', '+Employees.first_name -- delete
StandardQuery.client_id -- add