简体   繁体   English

PHP选择并按日期(月份和年份)以及用户分组

[英]PHP select and group by date (month and year) as well as user

I have a table that has info like this: 我有一张桌子,上面有这样的信息:

id | staff_id | start_date
1  | 14       | 2015-04-02 00:00:00
2  | 16       | 2015-04-15 00:00:00
3  | 14       | 2015-05-31 00:00:00
4  | 12       | 2015-05-04 00:00:00

What I am trying to do is select and count all entries made by each staff member and group them by month and year so it would display like this: 我想做的是选择并计算每个工作人员的所有条目,并按月和年对它们进行分组,以便显示如下:

Staff Member  | 12  | 14  | 16
2015-04       | 0   | 1   | 1
2015-05       | 1   | 1   | 0

Can anyone please help me to figure out how to generate this? 谁能帮我弄清楚如何产生这个吗? I just cant figure out how to create a new column for each staff member and also a row for each month/year. 我只是想不出如何为每个工作人员创建一个新列,以及为每个月/年创建一行。

This is a pivot query, but a bit complicated because of the dates: 这是一个枢轴查询,但是由于日期原因而有些复杂:

select date_format(start_date, '%Y-%m') as yyyymm,
       sum(staff_id = 12) as `12`, sum(staff_id = 14) as `14`,
       sum(staff_id = 16) as `16`
from table t
group by yyyymm;

If you don't know the staff ids in advance, then you'll need to use dynamic SQL. 如果您事先不知道职员编号,则需要使用动态SQL。 Google "MySQL dynamic pivot" to see how to do that. 谷歌“ MySQL动态枢纽”,看看如何做到这一点。

This is called cross tabulated query (aka pivot table). 这称为交叉列表查询(又称为数据透视表)。 MySql does not natively support such transformations. MySql本机不支持此类转换。

Possible solutions: 1. Generate the counts by user and month in the traditional way and then use php to transform the data into its final resultset. 可能的解决方案:1.以传统方式按用户和月份生成计数,然后使用php将数据转换为最终结果集。 2. Use a spreadsheet program (eg. Excel) to do the transformation for you again based on the traditional dataset. 2.使用电子表格程序(例如Excel)根据传统数据集再次为您进行转换。 3. There are ways to do it in MySql, see link1 , link2 3.在MySql中有多种方法可以执行此操作,请参见link1link2

The second link is a SO link. 第二个链接是SO链接。

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

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