我有3个包含相同字段的表(ticket1,ticket2,ticket3):
ticket1: ticket2: ticket2:
======== ======== ========
ticket_id ticket_id ticket_id
status status status
我的查询就是这样:
("SELECT (SELECT COUNT( * ) FROM `ticket1` WHERE `status` =9) AS done,
(SELECT COUNT( * ) FROM `ticket1` WHERE `status` =10) AS Incomplete,
(SELECT COUNT( * ) FROM `ticket1` WHERE `status` =2) AS New")
这是对票进行计数并按状态进行过滤。
我的问题是,如何从ticket1,ticket2,ticket3将所有票据计入完成,未完成和新的总数中。
帮我,谢谢。
答案 0 :(得分:0)
尝试一下。
select status, count(1) from
(select * from ticket1
union all
select * from ticket2
union all
select * from ticket3) group by status;
让我知道您是否遇到任何问题
答案 1 :(得分:0)
您可以从联合全部中选择
select sum(case when status = 9 then 1 else 0 end) done,
sum(case when status = 10 then 1 else 0 end) Incomplete,
sum(case when status = 2 then 1 else 0 end) New,
sum(case when status in (9,10,2) then 1 else 0 end) deon_incomplete_new,
count(*) tot
from (
select ticket_id, status from ticket1
union all
select ticket_id, status from ticket2
union all
select ticket_id, status from ticket2
) t
答案 2 :(得分:0)
我猜3d表的名称是ticket3
,对吧?
SELECT
(SELECT COUNT(*) FROM `ticket1` WHERE `status` = 9) +
(SELECT COUNT(*) FROM `ticket2` WHERE `status` = 9) +
(SELECT COUNT(*) FROM `ticket3` WHERE `status` = 9) AS TotalDone,
(SELECT COUNT(*) FROM `ticket1` WHERE `status` = 10) +
(SELECT COUNT(*) FROM `ticket2` WHERE `status` = 10) +
(SELECT COUNT(*) FROM `ticket3` WHERE `status` = 10) AS TotalIncomplete,
(SELECT COUNT(*) FROM `ticket1` WHERE `status` = 2) +
(SELECT COUNT(*) FROM `ticket2` WHERE `status` = 2) +
(SELECT COUNT(*) FROM `ticket3` WHERE `status` = 2) AS TotalNew
答案 3 :(得分:0)
我建议:
select sum(case when status = 9 then cnt else 0 end) as done,
sum(case when status = 10 then cnt else 0 end) as incomplete,
sum(case when status = 2 then cnt else 0 end) as new
from ((select status, count(*) as cnt from ticket1 group by status
) union all
(select status, count(*) as cnt from ticket2 group by status
) union all
(select status, count(*) as cnt from ticket3 group by status
)
) t;
或者,您可以考虑使用group by
将值放在单独的行中。
如果性能是一个问题,而您还有许多其他故障单状态(或更具体地说,许多具有不同状态的行),则每个子查询中的where status in (2, 9, 10)
可能会有所帮助。