MYSQL使用单个查询嵌套组

时间:2017-08-22 09:56:19

标签: mysql sql

我有一个带有以下架构的数据库

Id | Employee_Name | Time_Taken | Job_Number | Date

最后,对于任何给定的日期范围,我想要返回的是以下形式的结果

{  
   "Brad":[  
      {  
         "day":"1",
         "avg_time":"1.65"
      },
      {  
         "day":"2",
         "avg_time":"2"
      }
   ],
   "Emily":[  
      {  
         "day":"1",
         "avg_time":"1.65"
      },
      {  
         "day":"2",
         "avg_time":"2"
      }
   ]
   ..
}

因此,我希望向每位员工展示完成工作日所需的平均时间。

我能想到的是首先获得所有员工,然后对员工进行迭代,并为每个员工执行以下操作

SELECT DAYOFMONTH(FROM_UNIXTIME(date)), AVG(time_taken)
       FROM PerformanceTable WHERE (date BETWEEN x AND y AND employee_name=name)
       GROUP BY DAYOFMONTH(FROM_UNIXTIME(date));

请忽略查询中的任何轻微语法错误,但这是我的想法。我的问题是,有没有办法通过单个查询来完成,而不需要循环员工。谢谢!

1 个答案:

答案 0 :(得分:1)

我不会用“日期”来定义日期。只需将日期组件从date列中拉出(假设它有时间)。

然后,将employee_name添加到selectgroup by

select employee_name, date(from_unixtime(date)) as date,
       avg(time_taken)
from PerformanceTable pt
where date between x and y  -- assumes "x" and "y" are integers, not dates
group by employee_name, date(from_unixtime(date))
order by employee_name, date;