在MySQL中按月份和年份分组
给定一个每行有一个时间戳的表,你将如何格式化查询以适应这个特定的json对象格式。
我试图组织一个json对象到几年/几个月。
json将查询closures:
{ "2009":["August","July","September"], "2010":["January", "February", "October"] }
这是我到目前为止的查询 –
SELECT MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year FROM trading_summary t GROUP BY MONTH(t.summaryDateTime) DESC";
这个查询正在打破,因为它(可预测地)将不同的年份结合在一起。
GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime) DESC;
是你想要的。
GROUP BY DATE_FORMAT(summaryDateTime,'%Y-%m')
SELECT MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year FROM trading_summary t GROUP BY YEAR(t.summaryDateTime) DESC, MONTH(t.summaryDateTime) DESC
应该使用年和月的DESC来获得正确的顺序。
我更喜欢
SELECT MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year FROM trading_summary t GROUP BY EXTRACT(YEAR_MONTH FROM t.summaryDateTime) DESC";
你必须这样做
SELECT onDay, id, sum(pxLow)/count(*),sum(pxLow),count(`*`), CONCAT(YEAR(onDay),"-",MONTH(onDay)) as sdate FROM ... where stockParent_id =16120 group by sdate order by onDay
像这样使用EXTRACTfunction
mysql> SELECT EXTRACT(YEAR FROM '2009-07-02'); -> 2009
您只是按月分组,您必须将YEAR()添加到组中
SELECT YEAR(t.summaryDateTime) as yr, GROUP_CONCAT(MONTHNAME(t.summaryDateTime)) AS month FROM trading_summary t GROUP BY yr
你仍然需要在外部脚本中处理它,以获得你正在寻找的结构。
例如,使用PHP的explode从月份名称列表创build一个数组,然后使用json_encode()
使用
GROUP BY year, month DESC";
代替
GROUP BY MONTH(t.summaryDateTime) DESC";