我在mysql中选择查询时遇到问题。我在phpMyAdmin中的表是这样的:
------------------------------------
| Date_id | Date |
------------------------------------
| 1 | 2014-05-13 |
| 2 | 2014-06-04 |
| 3 | 2014-07-09 |
| 4 | 2014-08-13 |
| 5 | 2014-09-12 |
| 6 | 2014-10-15 |
| 7 | 2014-11-19 |
| 8 | 2014-12-10 |
| 9 | 2015-01-14 |
| 10 | 2015-02-11 |
| 11 | 2015-03-10 |
| 12 | 2015-04-15 |
| 13 | 2015-05-12 |
| 14 | 2015-06-12 |
------------------------------------
我期待的结果是这样的:
------------------------------------------------------------------------------------------
| Year | Jan | Feb | Mar | April | May | June | July | Aug | Sept | Oct | Nov | Dec |
------------------------------------------------------------------------------------------
| 2014 | | | | | 13 | 04 | 07 | 13 | 12 | 15 | 19 | 10 |
----------------------------------------------------------------------------------------
| 2015 | 14 | 11 | 10 | 15 | 12 | 12 | | | | | | |
----------------------------------------------------------------------------------------
如何将查询写入select语句?
答案 0 :(得分:1)
我认为最简单的方法是使用:
select year(`Date`) as `year`,
max(case when month(date) = 1 then day(`date`) end) as Jan,
max(case when month(date) = 2 then day(`date`) end) as Feb,
max(case when month(date) = 3 then day(`date`) end) as Mar,
max(case when month(date) = 4 then day(`date`) end) as Apr,
max(case when month(date) = 5 then day(`date`) end) as May,
max(case when month(date) = 6 then day(`date`) end) as Jun,
max(case when month(date) = 7 then day(`date`) end) as Jul,
max(case when month(date) = 8 then day(`date`) end) as Aug,
max(case when month(date) = 9 then day(`date`) end) as Sep,
max(case when month(date) = 10 then day(`date`) end) as Oct,
max(case when month(date) = 11 then day(`date`) end) as Nov,
max(case when month(date) = 12 then day(`date`) end) as Dec
from table t
group by year(date)
order by year(date)
答案 1 :(得分:1)
SELECT
YEAR(DATE) AS YEAR,
SUM(MONTH(DATE) = 1) AS JAN ,
SUM(MONTH(DATE) = 2) AS FEB ,
SUM(MONTH(DATE) = 3) AS MAR ,
SUM(MONTH(DATE) = 4) AS APR,
SUM(MONTH(DATE) = 5) AS MAY ,
SUM(MONTH(DATE) = 6) AS JUNE ,
SUM(MONTH(DATE) = 7) AS JULY ,
SUM(MONTH(DATE) = 8) AS AUG,
SUM(MONTH(DATE) = 9) AS SEP ,
SUM(MONTH(DATE) = 10) AS OCTOBER ,
SUM(MONTH(DATE) = 11) AS NOV ,
SUM(MONTH(DATE) = 12) AS DECE
FROM table_name
WHERE DATE >= NOW() - INTERVAL 4 YEAR
GROUP BY 1;
答案 2 :(得分:0)
试试这段代码:
<?php
// to get all 2014 dates...
$year = 2014;
$sql="SELECT * FROM tableName WHERE Year(dateColumnName) = '$year'";
?>