2013-02-12 18 views
0

我有以下的输出:MySQL的计数在一个请求几个表

[email protected] [~]# mysql -e "SELECT TABLE_ROWS from information_schema.Tables where TABLE_SCHEMA= 'testdb' && TABLE_NAME = 'requests';" 
    +------------+ 
    | TABLE_ROWS | 
    +------------+ 
    | 9566846 | 
    +------------+ 

    [email protected] [~]# mysql -e "select count(*) from testdb.requests where created_at like '2012%';" 
    +----------+ 
    | count(*) | 
    +----------+ 
    | 301438 | 
    +----------+ 
    [email protected] [~]# mysql -e "select count(*) from testdb.requests where created_at like '2013%';" 
    +----------+ 
    | count(*) | 
    +----------+ 
    | 24917 | 
    +----------+ 

如何会更好,使用MySQL的要求做同样的一个请求,让新的输出像

+------------------+-----------------------+ 
    | year    | count(*)    | 
    +------------------+-----------------------+ 
    | 2009    | 1066268    | 
    | 2010    | 6799553    | 
    | 2011    | 1374685    | 
    | 2012    | 301438    | 
    | 2013    | 24917     | 
    | total   | 9566846    | 
    +------------------+-----------------------+ 

谢谢你在前进,Evgheni

回答

1

试试这个

SELECT YEAR(created_at) AS `year`, 
     COUNT(*) AS `count` 
    FROM testdb.requests 
GROUP BY YEAR(created_at) 
UNION ALL 
SELECT 'total' AS `year`, 
     TABLE_ROWS AS `count` 
    FROM information_schema.Tables 
WHERE TABLE_SCHEMA= 'testdb' AND 
     TABLE_NAME = 'requests' 

SELECT YEAR(created_at) AS `year`, 
     COUNT(*) AS `count` 
    FROM testdb.requests 
GROUP BY YEAR(created_at) 
UNION ALL 
SELECT 'total' AS `year`, 
     COUNT(*) AS `year` 
    FROM testdb.requests 

它产生的输出是这样的:

+-------+-------+ 
| year | count | 
+-------+-------+ 
| 2012 |  6 | 
| 2013 |  7 | 
| total | 13 | 
+-------+-------+ 

这里是sqlfiddle

+0

非常感谢 – 2013-02-12 08:27:35

+0

非常欢迎。快乐的编码。 – peterm 2013-02-12 08:28:11

1

你可以尝试使用一组语句

select 
    DATE_FORMAT(created_at, '%d') as year, 
    count(*) as count 
from 
    testdb.requests 
group by year; 
+0

更少的代码,更实用,但 – 2013-02-12 08:26:31

+0

欢迎你我有一部分来自@peterm结合它。继续编码! – joese 2013-02-12 08:41:30

1

尝试使用聚合函数 -

SELECT 
    YEAR(created_at) yesr, 
    COUNT(*) cnt 
FROM 
    testdb.requests 
GROUP BY year; 

要计算WITH ROLLUP修饰符总使用 -

SELECT 
    YEAR(created_at) yesr, 
    COUNT(*) cnt 
FROM 
    testdb.requests 
GROUP BY year WITH ROLLUP;