我现在有2个查询,如果可能,我希望将其合并为1个。
我已经在Tickets_Open表中存储了已打开的票证,而在Tickets_Closed中已关闭了票证。两个表都有“ Date_Requested”和“ Date_Completed”列。我需要计算每天请求和完成的门票数量。
我的机票请求计数查询如下:
SELECT SUM(Count) AS TotalOpen, Date FROM(
SELECT COUNT(Ticket_Request_Code) AS Count, Date_Requested AS Date
FROM Tickets_Closed
WHERE Date_Requested >='2018-01-01 00:00:00'
GROUP BY(Date_Requested)
UNION
SELECT COUNT(Work_Request_Code) AS Count, Date_Requested AS Date
FROM Tickets_Open
WHERE Date_Requested >='2018-01-01 00:00:00'
GROUP BY(Date_Requested)
) AS t1 GROUP BY Date ORDER BY `t1`.`Date` DESC
我的票完成计数查询如下:
SELECT COUNT(Ticket_Request_Code) AS CountClosed, Date_Completed AS Date
FROM Tickets_Closed
Where Date_Completed >='2018-01-01 00:00:00'
GROUP BY(Date_Completed)
两个查询都返回正确的结果。对于打开,它返回列标题为Date和TotalOpen。如果要关闭,则返回列标题为Date和CountClosed。
是否可以使用以下列标题Date,TotalOpen,CountClosed返回它。
答案 0 :(得分:0)
您可以将它们组合为:
SELECT Date, SUM(isopen) as isopen, SUM(isclose) as isclose
FROM ((SELECT date_requested as date, 1 as isopen, 0 as isclose
FROM Tickets_Closed
WHERE Date_Requested >= '2018-01-01'
) UNION ALL
(SELECT date_requested, 1 as isopen, 0 as isclose
FROM Tickets_Open
WHERE Date_Requested >= '2018-01-01'
) UNION ALL
(SELECT date_closed as date, 0 as isopen, 1 as isclose
FROM Tickets_Closed
WHERE date_closed >= '2018-01-01'
)
) t
GROUP BY Date
ORDER BY Date DESC;
这假设Ticket_Request_Code
和Work_Request_Code
不是NULL
。如果确实使用COUNT()
检查NULL
值,则将条件添加到每个子查询的WHERE
子句中。
答案 1 :(得分:0)
此查询也使用日期上的FULL OUTER JOIN,但它正确地将打开/关闭计数加在一起以提供TotalOpen计数。对于一天中没有关闭任何票证的情况,这还将处理可能的NULL值。
{{1}}