简体   繁体   English

如何按月+年分组?

[英]How to group by month+year?

http://www.bioshapebenefits.nl/bioshapebenefits/en/news/donations.html http://www.bioshapebenefits.nl/bioshapebenefits/en/news/donations.html

As you see, here I have a long list of entries, sorted by date, very simple. 如您所见,这里有一长串条目,按日期排序,非常简单。 So in mysql there would only be the columns 'name' and 'date', for example. 因此,在mysql中,只有列'name'和'date',例如。 And if I'd want to make a list out of it with php that would also be very simple, just sorting by date. 如果我想用php创建一个列表,这也很简单,只需按日期排序。

But how would I put the months+years in between, as shown in the example? 但是,我如何将月份和年份放在两者之间,如示例所示? Like: 喜欢:

June 2010 2010年6月

  • Trala TRALA
  • Lala 拉拉
  • Wala 瓦剌

May 2010 2010年5月

  • Trala TRALA
  • Lala 拉拉
  • Wala 瓦剌

在SQL Server中,它将如下所示,我想想mysql有类似的东西:

GROUP BY Year(Date), Month(Date)

There's a dozen ways to skin this cat, but my approach would probably be like this (all rough code snippets, not a full implementation) 有十几种方法来修饰这只猫,但我的方法可能就是这样(所有粗略的代码片段,而不是完整的实现)

First, the query 一,查询

select `name`
     , month(`date`) as date_month
     , year(`date`) as date_year
  from [Table]
 order by `date` desc

Then, organize the data into the desired logical groups 然后,将数据组织到所需的逻辑组中

$templateData = array();
foreach ( $rows as $row )
{
  $templateData[$row->date_year][$row->date_month][] = $row->name;
}

Then, in a template 然后,在模板中

<?php foreach ( $templateData as $year => $months ) : ?>
  <?php foreach ( $months as $month => $names ) : ?>
    <h2><?php echo $month, ' ', $year; ?></h2>
    <ul>
      <?php foreach ( $names as $name ) : ?>
        <li><?php echo $name; ?></li>
      <?php endforeach; ?>
    </ul>
  <?php endforeach; ?>
<?php endforeach; ?>

We do tonnage of this month grouping. 我们做了本月分组的吨位。 I use this expression to truncate arbitrary timestamps to timestamps that represent the first of the month. 我使用此表达式将任意时间戳截断为表示该月中第一个的时间戳。

   TIMESTAMP(DATE_FORMAT(action_time,'%Y-%m-01'))

This does the same thing as the Oracle-ism TRUNC(action_time,'MM') 这与Oracle-ism TRUNC(action_time,'MM')

For example you could do 例如,你可以做到

SELECT COUNT(*) NUM, TIMESTAMP(DATE_FORMAT(t.action_time,'%Y-%m-01')) MONTH
FROM TABLE t
GROUP BY TIMESTAMP(DATE_FORMAT(t.action_time,'%Y-%m-01'))

This has the conceptual advantage that it maintains the timestampiness of the month-truncated data, so if you need to you can still compute time differences and do other timey and datey things if you need to. 这具有概念上的优势,即它保持月截断数据的时间戳,因此如果需要,您仍然可以计算时间差异,并在需要时执行其他有时间和日期的事情。

As ravern pointed out, there's a small performance penalty (but it isn't bad!). 正如ravern指出的那样,性能会受到很小的惩罚(但也不错!)。 Some of our table columns are loaded using this function so they're already month-truncated. 我们的一些表列使用此函数加载,因此它们已被月截断。

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

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