简体   繁体   English

按年份分组 SQL 查询结果

[英]Group SQL query results by year

I'm new in SQL and I need to group the results of a query by year.我是 SQL 新手,我需要按年份对查询结果进行分组。

In other words, I have this table structure: id | title | date换句话说,我有这个表结构: id | title | date id | title | date

My current query SELECT * FROM table我当前的查询SELECT * FROM table

My current result:我目前的结果:

array =>
  0 =>
    array =>
      ...
      'date' => string '2018-03-09'
  1 =>
    array =>
      ...
      'date' => string '2018-03-15'
  2 =>
    array =>
      ...
      'date' => string '2017-03-15'

And I need something like that:我需要这样的东西:

array =>
  0 =>
    array =>
      ...
      'date' => string '2018-03-09'
    array =>
      ...
      'date' => string '2018-03-15'
  1 =>
    array =>
      ...
      'date' => string '2017-03-15'

Thanks in advance for help :)预先感谢您的帮助:)

[EDIT] [编辑]

I finally found a way to do what I wanted:我终于找到了一种方法来做我想做的事:

$result = $sql->query("SELECT * FROM abstract ORDER BY date DESC");
$array = [];

forEach($result as $res) {
    $year = strtok($res['date'], '-');
    if (!isset($array[$year]))
        $array[$year][0] = $res;
    else
        array_push($array[$year], $res);
}
return $array;

如果您想按年份对数据进行分组。

    Select id,title,date,DATE_FORMAT(date, '%Y') YEAR_GRP from table group by YEAR_GRP

This is something you'll want to do in your query, as MySQL can do it much more efficiently, than PHP.这是您希望在查询中执行的操作,因为 MySQL 可以比 PHP 更有效地执行此操作。

The way to do it is to add a GROUP BY clause to your query, which will batch rows in your resultset into a single row, based on a grouping value, which in your case will be YEAR(date) , as you're looking to group items by the year component in each line's date.这样做的方法是在您的查询中添加一个GROUP BY子句,这将根据分组值将结果集中的行批处理为单行,在您的情况下为YEAR(date) ,如您所见按每行日期中的年份组件对项目进行分组。

Because you're still looking to have all the results returned, merely grouped by each distinct grouping value, you'll need to use an Aggregate Function to combine all the matching lines into an array of values.因为您仍然希望返回所有结果,只是按每个不同的分组值分组,所以您需要使用聚合函数将所有匹配的行组合成一个值数组。 Luckily MySQL has a function called json_objectagg which does exactly what you need.幸运的是,MySQL 有一个名为json_objectagg的函数,它可以完全满足您的需求。

So you'll end up with a query that looks something like:因此,您最终会得到一个类似于以下内容的查询:

SELECT year(`date`) AS `year`, json_objectagg(id, `date`, title) AS `line`
FROM abstract
GROUP BY `year`

Instead of json_objectagg , alternatives are eg json_arrayagg而不是json_objectagg ,替代品是例如json_arrayagg

SELECT year(`date`) AS `year`, json_arrayagg(id, `date`, title) AS `line`

...or group_concat ...或group_concat

SELECT year(`date`) AS `year`, group_concat(id, `date`, title) AS `line`

...depending on what kind of output you require. ...取决于您需要什么样的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM