简体   繁体   English

如何在mysql中按季度分组日期并在php中检索

[英]How to group date by quarter in mysql and retrieve in php

I have a table that contains product orders and the date they were ordered. 我有一个包含产品订单及其订购日期的表格。 The date was inserted into the table using DATE(). 使用DATE()将日期插入到表中。 The customers can get a statistic of these orders by choosing to view by month, quarterly, yearly or total. 通过选择按月,按季度,按年或总计进行查看,客户可以获得这些订单的统计信息。 I need to retrieve every order since the beginning so there is no start date, only end date (today) and they need to be sorted. 我需要检索自开始以来的每个订单,因此没有开始日期,只有结束日期(今天),并且需要对其进行排序。

So, if they select quarterly, (the database starts in 2006), then it needs to display every order from 2006, quarterly and then with PHP, I need to display it like so: 因此,如果他们选择按季度(数据库从2006年开始),则它需要显示2006年以来的每个订单,按季度显示,然后使用PHP,我需要这样显示:

Quarter 1 - 2006 第1季-2006年


date , product1, quantity, price 日期,产品1,数量,价格
date , product2, quantity, price 日期,产品2,数量,价格

Quarter 2 - 2006 第2季-2006年


date , product1, quantity, price 日期,产品1,数量,价格
date , product2, quantity, price 日期,产品2,数量,价格

.
.
.

Quarter 1 - 2014 2014年第1季度


date , product1, quantity, price 日期,产品1,数量,价格
date , product2, quantity, price 日期,产品2,数量,价格

Is there a way to sort it like that? 有没有办法像这样排序? I can add things like quantity, price and product name myself. 我可以自己添加数量,价格和产品名称之类的东西。 I'm interested in figuring out how to sort the dates like that when the field in the database was populated using DATE (). 我想弄清楚如何使用DATE()填充数据库中的字段时对日期进行排序。 I hope the question is clear enough. 我希望这个问题足够清楚。 Thank you. 谢谢。

Have you tried using mySQL's QUARTER(date) function? 您是否尝试过使用MySQL的QUARTER(date)函数? If you want to sort after your retrieval rather than during it, add a column to your output and populate it with QUARTER(date), and then sort by that column. 如果要在检索之后而不是在检索过程中进行排序,请在输出中添加一列,并使用QUARTER(date)进行填充,然后按该列进行排序。

An easy way to do this would be to figure out a starting point first 一种简单的方法是首先确定一个起点

select YEAR(date_column) as min_year, QUARTER(date_column) as min_quarter from table order by date_column limit 1;

then you can do the printing in PHP starting from that index: 那么您可以从该索引开始用PHP进行打印:

for($i=$min_year; $i <= date('Y'); $i++){
    for($j=$min_quarter; $j<=ceiling(date('m')); $j++){
        echo "Quarter $j - $i";
        mysql_query("SELECT date, product, quantity, price FROM table WHERE QUARTER(date)=$j and YEAR(date)=$i ORDER BY date");
        //print your rows
        echo "\n";
    }
}

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

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