在新数据集中,我创建了两个新列,Start_time和End_time。我还要创建一个列,显示这两次之间的差异。这是我的代码:
SELECT b.company,
b.NAME,
Max(
CASE
WHEN description = 'Green' THEN final_value
END) AS 'Start_Time',
Max(
CASE
WHEN description = 'Red' THEN final_value
END) AS 'End_Time',
cast(datediff(n,
CASE('End_Time' as datetime),
CASE('Start_Time' AS datetime)) AS float) / 60 AS time_duration
FROM mydata a
JOIN ref_val b
ON a.ref_res = b.ref_res
WHERE b.company = 'abc'
GROUP BY b.company ,
b.NAME
当我运行此代码时,我收到一条错误消息,指出End_Time无法绑定。有什么建议?谢谢!
答案 0 :(得分:2)
您可以使用子查询来使用您创建的别名,也可以使用float类型在mysql中转换值。
SELECT *, CAST(DATEDIFF(n, CAST(End_Time AS datetime), CAST(Start_Time AS datetime)) AS DECIMAL(10,2)) / 60 AS Time_Duration
FROM (SELECT B.COMPANY
,B.NAME
,MAX(case when DESCRIPTION = 'Green' then Final_Value end) as Start_Time
,MAX(case when DESCRIPTION = 'Red' then Final_Value end) as End_Time
FROM mydata a
JOIN ref_val B
ON A.ref_res = B.ref_res
WHERE B.COMPANY = 'abc'
GROUP BY B.COMPANY
,B.NAME
) C