我有支持票据数据库,它们分为两个表,比如Incidents
,Tasks
。
Incidents
包含字段assigned_group
,open_time
,close_time
Tasks
包含字段assignment
,issue_date
,close_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
请注意,在每个查询中,行数(组)数可能不同,例如在特定时期没有打开任务,但有些任务已经关闭,这仍应计算在内
谢谢!
答案 0 :(得分:1)
我是否正确地想要获得加入Q1和Q3所需的已开启事件和任务的总数(假设assigned_group
和assignment
对加入有效)?如果是,则以下子选项将返回打开事件的总数
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,