这是一个完美的例子,但我必须在下面的示例中手动提及日期和状态,如何在数据库表中选择所有可用的日期和状态。
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 |