SQL查询组合来自不同表的报告

时间:2014-04-09 09:54:46

标签: sql sql-server-2008

我有支持票据数据库,它们分为两个表,比如IncidentsTasks
Incidents包含字段assigned_groupopen_timeclose_time
Tasks包含字段assignmentissue_dateclose_date(含义相同但名称不同)

现在我需要的是在特定时间段内编译以下结构的报告:

Group | Total opened incidents + tasks | Total closed incidents + tasks)

单个查询将如下所示:

-- Q1: Total opened incidents
SELECT assigned_group, COUNT(*) FROM incidents WHERE open_time BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' GROUP BY assigned_group

-- Q2: Total closed incidents
SELECT assigned_group, COUNT(*) FROM incidents WHERE close_time BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' GROUP BY assigned_group

-- Q3: Total opened tasks
SELECT assignment, COUNT(*) FROM tasks WHERE issue_date BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' GROUP BY assignment

-- Q4: Total closed tasks
SELECT assignment, COUNT(*) FROM tasks WHERE close_date BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' GROUP BY assignment

结果表应为

Group | Q1+Q3 | Q2+Q4

请注意,在每个查询中,行数(组)数可能不同,例如在特定时期没有打开任务,但有些任务已经关闭,这仍应计算在内

谢谢!

2 个答案:

答案 0 :(得分:1)

我是否正确地想要获得加入Q1和Q3所需的已开启事件和任务的总数(假设assigned_groupassignment对加入有效)?如果是,则以下子选项将返回打开事件的总数

SELECT Incidents.IncidentCount + Tasks.TaskCount AS TotalOpenIncidents ,
       COALESCE(Incidents.assigned_group, Tasks.assignment) AS Group
FROM (
    SELECT assigned_group, COUNT(*) AS IncidentCount 
    FROM incidents 
    WHERE open_time BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' 
    GROUP BY assigned_group ) AS Incidents INNER JOIN
    (
    SELECT assignment, COUNT(*) AS TaskCount
    FROM tasks 
    WHERE issue_date BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' 
    GROUP BY assignment) AS Tasks ON Incidents.assigned_group = Tasks.assignment

您需要对Q2和Q4执行相同操作以获得已关闭的计数

答案 1 :(得分:0)

要将这类数据粘贴在一起,您可以使用“完全外部连接”。或UNION ALL。这是UNION ALL方法:

有一些方法可以将此查询重构为更简单。如果您有兴趣,我可以向您展示,或者您可以自己尝试。例如,在Z子表中只需要2个查询。

如果您的连接列不是唯一的,UNION ALL方法会停止重复计算(尽管在您的情况下这不是问题)

SELECT assigned_group, SUM(Closed) As Closed, SUM(Opened) As Opened
FROM
(
SELECT assigned_group, COUNT(*) As Closed, 0 As Opened
FROM incidents 
WHERE open_time BETWEEN '2014-01-01     00:00:00' AND '2014-02-01 00:00:00' 
GROUP BY assigned_group

UNION ALL

SELECT assigned_group, 0 As Closed, COUNT(*) As Opened
FROM incidents 
WHERE close_time BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' 
GROUP BY assigned_group

UNION ALL

SELECT assignment, 0 As Closed, COUNT(*) As Opened
FROM tasks 
WHERE issue_date BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' 
GROUP BY assignment

UNION ALL

SELECT assignment, COUNT(*) As Closed, 0 As Opened
FROM tasks 
WHERE close_date BETWEEN '2014-01-01 00:00:00' AND '2014-02-01 00:00:00' 
GROUP BY assignment
) Z
GROUP BY assigned_group,