0

数据源是:

Start Time              Real End Time           Staff
2013-02-14 16:44:27     2013-02-14 18:44:27     P 
2013-02-14 16:44:08     2013-02-14 17:09:08     C
2013-02-14 16:42:51     2013-02-14 16:43:51     P
2013-02-14 16:31:26     2013-02-14 17:06:26     V
2013-02-14 16:04:02     2013-02-14 16:34:02     C

当我使用时:

CREATE VIEW turn_times AS
SELECT staff AS name, start_time, real_end_time AS work_end_time
FROM (  SELECT staff, start_time, real_end_time
        FROM treatments 
        WHERE date(real_end_time) = curdate()
        ORDER BY real_end_time ASC) AS a
GROUP BY name

我有:

mysql #1349 - View's SELECT contains a subquery in the FROM clause

我想通过使用 view获取以下数据,有什么好的解决方案:

name    start_time             work_end_time
C       2013-02-14 16:04:02    2013-02-14 16:34:02
P       2013-02-14 16:42:51    2013-02-14 16:43:51
V       2013-02-14 16:31:26    2013-02-14 17:06:26

我不想为这个问题创建两个视图,我可以在一个视图中获得正确的 sql 吗?

4

2 回答 2

0

ORDER BY您是否尝试使用聚合函数 ( MIN) 来返回min()每个的日期,而不是使用带有 的子查询staff

SELECT staff, 
  min(start_time),
  min(real_end_time)AS work_end_time
FROM treatments 
WHERE date(real_end_time) = curdate()
group by staff

请参阅SQL Fiddle with Demo

然后变成一个视图:

CREATE VIEW turn_times AS
SELECT staff, 
  min(start_time),
  min(real_end_time)AS work_end_time
FROM treatments 
WHERE date(real_end_time) = curdate()
group by staff

上面的这个版本复制了您提供的结果,但如果您想要结束时间,您可能需要使用以下内容。这将为您提供每个员工的实际开始时间和结束时间:

CREATE VIEW turn_times AS
SELECT staff, 
  min(start_time) as start_time,
  max(real_end_time) AS work_end_time
FROM treatments 
WHERE date(real_end_time) = curdate()
group by staff

请参阅带有演示的 SQL Fiddle

于 2013-02-14T11:27:17.103 回答
0

目前尚不清楚您为什么使用子查询,但您可以在没有子查询的情况下获得类似的结果

CREATE VIEW turn_times AS
SELECT staff AS name, 
  MIN(start_time) AS start_time,
  MAX(real_end_time) AS work_end_time,
  date(start_time) As turn_date
FROM treatments 
WHERE 
AND date(start_time) = curdate()
AND date(real_end_time) = curdate()
GROUP BY staff, date(start_time);
于 2013-02-14T11:32:22.303 回答