计算一个交叉连接,在T-SQL内加一个

时间:2015-07-22 09:02:40

标签: sql sql-server tsql

我正在尝试为我们的事件管理软件编写查询,该软件将为每位工程师报告他们今天关闭的请求数量以及今天记录的操作时间。数据存储在四个主表中:

  • 人员 - 工程师的姓名和ID
  • ArchiveRequests - 支持请求
  • ArchiveReqSLA - 请求的时间相关详细信息
  • ArchiveActions - 对请求的操作

这是我到目前为止提出的查询:

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

我的结果怎么了?

1 个答案:

答案 0 :(得分:1)

请勿使用联接。这就是你想要做的:

  1. 报告,每个工程师,
    1. 工程师详情,
  2. 他们今天关闭的请求数量
    1. 请求数
    2. 那个人
    3. 今天关闭
  3. 今天登录行动的时间
    1. 总时间
    2. 由他们
    3. 今天的行动
  4. 因此,将其直接转换为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