如何为MySQL中的每个数据库的一个表计算不同的列值

时间:2017-05-09 16:55:28

标签: mysql database

我遇到这种情况,其中有几个数据库具有相同的表名和不同的信息。

我想键入一个查询,我可以在其中获取给定列的不同值,然后获取每个database.table和每个列值的计数,如下所示:

表:项目(在每个数据库中找到):

status - quantity(DB1) - Quantity(DB2) - Quantity(DB3)
In progress - 147 - 141 - 135
Cancelled   - 2 - 1 - 4
Finished    - 45 - 52 - 64

我如何实现这一目标?

我尝试了以下(以及其他解决方法):

SELECT p2012.STATUS AS 'Status',COUNT(p2012.STATUS) AS 'Quantity' ,COUNT(DB2013.STATUS) AS 'Quantity'
FROM DB2012.projects AS p2012, DB2013.projects AS p2013
GROUP BY p2012.STATUS

但我得到以下相同数量和大数字:

status - quantity(DB1) - Quantity(DB2) - Quantity(DB3)
    In progress - 13447 - 13447 - 13447
    Cancelled   - 3434 - 3434 - 3434
    Finished    - 4344 -4344 - 4344

有关如何解决此问题的任何想法?

解决在GiancarloBenítez的帮助下:

(
SELECT '2012' AS 'year',A.InProgress AS 'InProgress',B.Restarted AS 'Restarted',C.Cancelled AS 'Cancelled',D.Finished AS 'Finished' FROM
(SELECT status, count(*) AS 'InProgress' FROM DB2012.projects WHERE status='PRO') AS A,
(SELECT status, count(*) AS 'Restarted' FROM DB2012.projects WHERE status='RES') AS B,
(SELECT status, count(*) AS 'Cancelled' FROM DB2012.projects WHERE status='CAN') AS C,
(SELECT status, count(*) AS 'Finished' FROM DB2012.projects WHERE status='FIN') AS D
)
UNION
(
SELECT '2013' AS 'year',A.InProgress AS 'InProgress',B.Restarted AS 'Restarted',C.Cancelled AS 'Cancelled',D.Finished AS 'Finished' FROM
(SELECT status, count(*) AS 'InProgress' FROM DB2013.projects WHERE status='PRO') AS A,
(SELECT status, count(*) AS 'Restarted' FROM DB2013.projects WHERE status='RES') AS B,
(SELECT status, count(*) AS 'Cancelled' FROM DB2013.projects WHERE status='CAN') AS C,
(SELECT status, count(*) AS 'Finished' FROM DB2013.projects WHERE status='FIN') AS D
)
UNION
...

1 个答案:

答案 0 :(得分:1)

你应该为每个人做几个查询,然后把它们放在一起,比如:

select A.status, A.counts, B.status, B.counts 
from 
(select status, count(*) as counts from DB2012.projects where status = 'In progress') as A, 
(select status, count(*) as counts from DB2012.projects where status = 'Cancelled') as B;

这会让你得到像

这样的东西
In progress - 123 - Cancelled   - 876

所有在同一行,然后你可以处理它,把它放在一个表中,如你所愿。