简体   繁体   English

SQL 返回月/年 col 和 COUNT 的命令

[英]SQL Command that Returns Month/Year col and COUNT

I've been trying this for sometime, and appear to have hit a roadblock.我已经尝试了一段时间,但似乎遇到了障碍。

I want to group and count Hours by month.我想按月分组和计算小时数。

My SQL Table:我的 SQL 表:

id ID Date日期 Hours小时
1 1个 1645176391 1645176391 2.1 2.1
1 1个 1645435591 1645435591 1.6 1.6
1 1个 1642152391 1642152391 1.4 1.4
1 1个 1647246391 1647246391 1.7 1.7
2 2个 1647246391 1647246391 2.5 2.5
1 1个 1647591991 1647591991 0.4 0.4

My current attempt:我目前的尝试:

SELECT FROM_UNIXTIME(Date, '%m-%Y') AS prod_month, COUNT(Hours)
            FROM my_table
            WHERE Date > [last 365 days in unix timestamp]
            AND id = 1
            GROUP BY
            prod_month;"

So, ideally the result would return something like:因此,理想情况下,结果会返回如下内容:

prod_month生产月份 Hours小时
02-2022 02-2022 3.7 3.7
01-2022 01-2022 1.4 1.4
03-2022 03-2022 2.1 2.1

Made three tweaks to your query:对您的查询进行了三处调整:

  • adopted SUM instead of COUNT , to sum up hours采用SUM而不是COUNT ,来总结小时数
  • added ROUND to round your sum to two numbers添加ROUND将您的总和四舍五入为两个数字
  • used UNIX_TIMESTAMP to transform current date in unixtime and make comparison in the WHERE clause使用UNIX_TIMESTAMP将当前日期转换为 unixtime 并在WHERE子句中进行比较
SELECT FROM_UNIXTIME(Date_, '%m-%Y') AS prod_month, 
       ROUND(SUM(Hours),2)           AS Hours 
FROM my_table
WHERE UNIX_TIMESTAMP(CURDATE() - INTERVAL 1 YEAR) < Date_
  AND id = 1
GROUP BY FROM_UNIXTIME(Date_, '%m-%Y')

Check the demo here .此处查看演示。

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

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