0

我有以下输出:

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

    root@localhost [~]# mysql -e "select count(*) from testdb.requests where created_at like '2012%';"
    +----------+
    | count(*) |
    +----------+
    |   301438 |
    +----------+
    root@localhost [~]# 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

4

3 回答 3

1

您可以尝试使用 group 语句

select 
    DATE_FORMAT(created_at, '%d') as year, 
    count(*) as count
from
    testdb.requests
group by year;
于 2013-02-12T07:27:18.647 回答
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;
于 2013-02-12T07:32:02.040 回答
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

于 2013-02-12T07:34:08.660 回答