我正在尝试为我们的事件管理软件编写查询,该软件将为每位工程师报告他们今天关闭的请求数量以及今天记录的操作时间。数据存储在四个主表中:
这是我到目前为止提出的查询:
SELECT FirstName,
LastName,
count(ArchiveRequests.RequestId) AS TicketsClosed,
SUM(TimeUsed) AS TimeUsed
FROM ArchiveRequests
INNER JOIN People ON ArchiveRequests.AssignedToId = People.PersonId
INNER JOIN ArchiveReqSLA ON ArchiveReqSLA.RequestId = ArchiveRequests.RequestId
WHERE
CONVERT(date, Closed) = @Date
AND ArchiveRequests.StatusId IN (
SELECT StatusId
FROM Status
WHERE Closed = 1
)
GROUP BY FirstName, LastName
这非常有用,并产生以下内容:
Name Tickets
Mr X 16
Ms Y 11
Mr Z 10
...
然后我去添加花费的时间,并提出以下内容:
SELECT FirstName,
LastName,
COUNT(ArchiveRequests.RequestId) AS Tickets,
SUM(TimeUsed) AS TimeUsed
FROM ArchiveRequests
INNER JOIN People ON ArchiveRequests.AssignedToId = People.PersonId
INNER JOIN ArchiveReqSLA ON ArchiveReqSLA.RequestId = ArchiveRequests.RequestId
INNER JOIN archiveActions ON ArchiveActions.ActionedById = People.PersonId
WHERE
CONVERT(date, ArchiveActions.ActionDate) = @Date
AND CONVERT(date, Closed) = @Date
AND ArchiveRequests.StatusId IN (
SELECT StatusId
FROM Status
WHERE Closed = 1
)
GROUP BY FirstName, LastName
然而,这会返回太高的数字,并且也会中断票号:
Name Tickets Time
Mr X 416 2064
Ms Y 290 2010
Mr Z 242 2574
我的结果怎么了?
答案 0 :(得分:1)
请勿使用联接。这就是你想要做的:
因此,将其直接转换为SQL,如下所示:
select
-- 1.1. engineer details
p.PersonId, p.firstname, p.lastname,
-- 2. the number of request they closed today
(
-- 2.1 the number of requests
select count(1)
from ArchiveRequests ar
-- 2.2 By that person
where ar.AssignedToId = p.personId
-- 2.3 closed today
and CONVERT(date, Closed) = @Date
) as TicketsClosed,
-- 3. The time logged today
(
select sum(TimeUsed)
from ArchiveActions aa
where aa.ActionedById = p.PersonId
and CONVERT(date, aa.actionDate) = @date
) as TimeUsed
-- 1. report, for each engineer,
from People p