【问题标题】:select distinct years and their months in a single query在单个查询中选择不同的年份和月份
【发布时间】:2012-08-22 12:08:57
【问题描述】:

如何在单个查询中从时间戳列中选择不同年份和不同月份,如下所示

我试过select distinct year(sc_ts) as years from posts where user_id = 1 order by years asc 我不知何故无法将月份部分放在那里。或者这需要两个不同的语句和php处理。

我打算将其输出为

2009 - Mar, Apr, May
2010 - Apr, Jun, Jul

"2009-03-22 16:07:48"
"2009-04-22 16:07:48"
"2009-05-22 16:07:48"
"2010-04-22 16:07:48"
"2010-06-22 16:07:48"
"2010-07-22 16:07:48"
"2011-01-22 16:07:48"
"2011-02-22 16:07:48"
"2011-05-22 16:07:48"
"2011-06-22 16:07:48"
"2011-08-22 16:07:48"
"2012-01-22 16:07:48"
"2012-02-22 16:07:48"
"2012-03-22 16:07:48"
"2012-04-22 16:07:48"
"2012-08-22 16:07:48"

【问题讨论】:

    标签: php mysql


    【解决方案1】:
    select distinct year(sc_ts) as years, group_concat(monthname(sc_ts)) as months from posts where user_id = 1 order by years asc
    

    编辑:我最初使用month(),它给出了月份编号,使用monthname()返回月份的名称。

    【讨论】:

    • 这很近了,但事情是它会给你一年和所有年份的所有月份 2009 年,三月,四月,五月,四月,六月,七月,一月,二月,五月,六月,八月,一月,二月,三月,四月,八月
    【解决方案2】:
    SELECT x.`Year`, GROUP_CONCAT(x.`Month`) AS Months
    FROM
        (
            SELECT DISTINCT YEAR(sc_ts) AS `Year`, MONTHNAME(sc_ts) AS `Month`
            FROM
                `posts`
            WHERE
                user_id = 1
            ORDER BY
                MONTH(sc_ts)
        ) x
    GROUP BY
        x.`Year`
    ORDER BY
        x.`Year`
    

    【讨论】:

    • 耶稣...多好的查询 :) 我什至不知道这样的事情(子查询)是可能的。我今晚必须调查一下。顺便说一句,这可以 100% 完成这项工作。谢谢
    【解决方案3】:

    试试SELECT distinct SUBSTRING(year(sc_ts), 6)

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多