简体   繁体   English

选择特定用户的特定月份和年份的小时数

[英]Select Sum of hours for specific month and year for specific user

Hello I am trying to realize a query where from DB with hours and dates I can select sum of all hours for certain department, in certain year. 您好我正在尝试实现查询,其中来自数据库的小时和日期我可以选择特定部门的所有小时的总和,在某些年份。

Table example is the following: 表示例如下:

在此输入图像描述

So far the query which I am generating is the following: 到目前为止,我生成的查询如下:

    SELECT t.clientid, t.date, t.department, t.time,
                        (SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `time` ) ) ) FROM time_management  WHERE YEAR(t.date)='$year' AND MONTH(t.date)= 12 GROUP BY t.clientid ) as january,
                        (SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `time` ) ) ) FROM time_management  WHERE YEAR(t.date)='$year' AND MONTH(t.date)= 2 GROUP BY t.clientid ) as february
                        FROM time_management t GROUP by t.clientid

What I would like this to do is select sum of all hours for the month of January 2016. in the current state I am getting the result of sum of all hours for all clients and I would like to get result for client by client: 我想要做的是选择2016年1月所有小时的总和。在当前状态下,我得到所有客户的所有小时总和的结果,我想得到客户的结果:

Current Result is: 目前的结果是:

在此输入图像描述

So what I am searching for is how to get the sum of the times result grouped by clientid and get 2 results not only one. 所以我要搜索的是如何获得按clientid分组的时间总和,得到2个结果不仅仅是一个。 The sum for both client id. 两个客户端ID的总和。 independently summed for each one of them ? 为他们每个人独立总结?

Any help will be very appreciate. 任何帮助将非常感激。 Thank you! 谢谢!

You should be able to do that without the subquery - 你应该能够在没有子查询的情况下做到这一点 -

SELECT `date`, `department`, SUM(`time`)
    FROM `time_management`
    WHERE YEAR(`date`)='$year' AND MONTH(`date`)= 12
    GROUP BY `client_id`

I recommend you store you time in the database in seconds - the only time it needs to show as hours and minutes is when it's formatted to show on the client's screen. 我建议你在几秒钟内将时间存储在数据库中 - 它需要显示的时间是小时和分钟,它是格式化显示在客户端屏幕上的时间。 If you do store it as strings, you will have to put all that converting stuff back in. 如果你把它存储为字符串,你将不得不把所有转换的东西都放回去。

Looking at it more, I'd also recommend storing your year and month either as separate columns, or as integers based on a pattern: 201612, perhaps, or something like that. 再看一下,我还建议将您的年份和月份存储为单独的列,或者根据模式存储整数:201612,或许类似的东西。 That will clean up your where clause as well. 这也将清理你的where子句。

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

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