计算php和mysql中一系列日期的每个状态的条目总数

时间:2013-12-14 17:15:48

标签: php mysql

我的用户根据数据库中各州的日期进行了注册。

问:我想构建一个表格,显示一系列日期的每个州注册的总用户数,总计列数和行数。这可能吗?类似下表这样的内容

    2013-10-01    2013-10-02    2013-10-03    2013-10-04    2013-10-05    TOTAL

NY:   125            110          102           98            75           510
MN:   21              56           78           41            22           218
CO:   17              41           52           51            56           217
TX:   10             102           45           62            21           240
NO:   59              85           78           48            98           368

TOTAL 232            394          355           300           272         1553 

我一直致力于以下查询

if ($_GET) {
$dateF = date('Y-m-d', strtotime($_GET['datefrom']));
$dateT = date('Y-m-d', strtotime($_GET['dateto']));

$db = new PDO('mysql:host=localhost;dbname=database;charset=utf8', 'username', 'pass');

$stmt = $db->query("
    SELECT   `Date`, COUNT(*) AS `count_num`
    FROM     `table`
    WHERE    `Date` BETWEEN '$dateF' AND '$dateT'
    GROUP BY `Date`
    ORDER BY `Date` ASC
");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        echo "<tr>
                <td>" . $row["Date"] . "</td>
                <td>" . $row["count_num"] . "</td>

              </tr>";
        }

上面的查询只给出了每个日期的数据,但是对于所有状态的组合。像这样的东西

Date         Total
2013-10-01    564
2013-10-02    124
2013-10-03    521 
etc..

我也尝试过以下查询

$stmt = $db->query("SELECT state, COUNT(*) cnt1 FROM `table` WHERE Date between '$datefrom' AND '$dateto' GROUP BY state;");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>
   <td>" . $row["state"] . ":</td>
   <td>" . $row["cnt"] . "</td>
 </tr>";

}

但这仅显示输入日期范围的每个州的总数据。像这样的东西

NY: 125
MN: 21
CO: 17
TX: 10
NO: 59

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您需要一种名为枢轴查询的内容。

一个简单的例子 - &gt; http://www.sqlfiddle.com/#!2/6fc8b/1

SELECT state,
       SUM( if( date='2013-10-01', 1, 0) ) `2013-10-01`,
       SUM( if( date='2013-10-02', 1, 0) ) `2013-10-02`, 
       SUM( if( date='2013-10-03', 1, 0) ) `2013-10-03`
       --  .........   
       --  .........  
       --  .........  
FROM `table`
GROUP BY state;

| STATE | 2013-10-01 | 2013-10-02 | 2013-10-03 |
|-------|------------|------------|------------|
|    CO |          4 |          2 |          3 |
|    NY |          3 |          1 |          0 |
|    TX |          1 |          0 |          4 |


SELECT `date`,
       SUM( CASE state WHEN 'NY' THEN 1 ELSE 0 END ) `NY`,
       SUM( CASE state WHEN 'CO' THEN 1 ELSE 0 END ) `CO`,
       SUM( CASE state WHEN 'TX' THEN 1 ELSE 0 END ) `TX`
       --  .........  
       --  .........  
       --  .........  
FROM `table`
GROUP BY `date`

|                           DATE | NY | CO | TX |
|--------------------------------|----|----|----|
| October, 01 2013 00:00:00+0000 |  3 |  4 |  1 |
| October, 02 2013 00:00:00+0000 |  1 |  2 |  0 |
| October, 03 2013 00:00:00+0000 |  0 |  3 |  4 |