将日期列表除以月份SQL

时间:2019-01-31 12:01:31

标签: mysql mysql-workbench

我有ID的列表以及它们出现的日期。

id|date
1 |2019-01-22
2 |2019-02-13
etc

我想要一个只按月列出ID的表。我有

SELECT 
        `a`.`sourceID` AS `Jan 2019`
    FROM
        `all_dates` `a`
    WHERE
        ((MONTH(`a`.`next1`) = 1)
            AND (YEAR(`a`.`next1`) = 2019))

作为一栏,我希望在2019年每个月12栏。我不希望有工会(据我所知)。我不确定是否只是为子查询输入了错误的语法,或者是否需要使用联接等。

(SELECT 
        `a`.`sourceID`
    FROM
        `all_dates` `a`
    WHERE
        ((MONTH(`a`.`next1`) = 1)
            AND (YEAR(`a`.`next1`) = 2019))) AS `Jan 2019`,
(SELECT 
        `a`.`sourceID`
    FROM
        `all_dates` `a`
    WHERE
        ((MONTH(`a`.`next1`) = 2)
            AND (YEAR(`a`.`next1`) = 2019))) AS `Feb 2019`

我收到上面的“子查询返回多于1行”的错误。我是在正确的路线上并且只需要清理它,还是应该做其他事情?

我想要的结果应该像

|jan-2019|feb-2019
| 1      |2
| 4      |3

1 个答案:

答案 0 :(得分:0)

以下查询是间接查询,输出也有不满足条件的空值,请尝试

 SELECT 
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '01') THEN `tablename`.`id`
        ELSE NULL
    END) AS `jan_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '02') THEN `tablename`.`id`
        ELSE NULL
    END) AS `feb_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '03') THEN `tablename`.`id`
        ELSE NULL
    END) AS `mar_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '04') THEN `tablename`.`id`
        ELSE NULL
    END) AS `apr_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '05') THEN `tablename`.`id`
        ELSE NULL
    END) AS `may_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '06') THEN `tablename`.`id`
        ELSE NULL
    END) AS `jun_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '07') THEN `tablename`.`id`
        ELSE NULL
    END) AS `jul_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '08') THEN `tablename`.`id`
        ELSE NULL
    END) AS `aug_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '09') THEN `tablename`.`id`
        ELSE NULL
    END) AS `sep_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '10') THEN `tablename`.`id`
        ELSE NULL
    END) AS `oct_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '11') THEN `tablename`.`id`
        ELSE NULL
    END) AS `nov_2019`,
    (CASE
        WHEN (SUBSTR(`tablename`.`dd`, 6, 2) = '12') THEN `tablename`.`id`
        ELSE NULL
    END) AS `dec_2019`
FROM
    `tablename`;