2012-09-10 41 views
2

我有一個查詢,我已簡化並寫在下面。 如何顯示計算爲2個獨立內聯選擇語句的2個字段的時差?計算從2個獨立的行內選擇語句中提取的值

SELECT x.name , 
    (SELECT data.ts 
    FROM data 
    WHERE prim_key = x.prim_key and roll_no ='1' 
) **starttime** , 
    (SELECT data.ts 
    FROM woman_data 
    WHERE prim_key = x.prim_key and roll_no ='10' 

) **endtime** 
, **TIME_TO_SEC(TIMEDIFF(endtime , starttime)** as timediff // This line does not work.It cannot recognize endtime ans starttime 
FROM data x 
    INNER JOIN y 
ON x.prim_key = y.prim_key 
ORDER BY x.prim_key 

回答

0

試試這個:

開始時間和結束時間是派生列,你不能在使用它相同的選擇語句。 您必須創建派生表,然後使用這些列外部查詢一個查詢

select name,starttime,endtime,TIME_TO_SEC(TIMEDIFF(endtime , starttime) as timediff 
from(
SELECT x.name , 
    (SELECT data.ts 
    FROM data 
    WHERE prim_key = x.prim_key and roll_no ='1' 
) starttime , 
    (SELECT data.ts 
    FROM woman_data 
    WHERE prim_key = x.prim_key and roll_no ='10' 

) endtime 

FROM data x 
    INNER JOIN y 
ON x.prim_key = y.prim_key)a 
ORDER BY x.prim_key 
+0

謝謝..工作對我來說非常好。 – user1606540

0

更改查詢有一個「外部級」的最簡單方法:

SELECT 
name, 
starttime, 
endtime, 
TIME_TO_SEC(TIMEDIFF(endtime , starttime)) as timediff 
FROM(
SELECT 
x.prim_key, 
x.name , 
    (SELECT data.ts 
    FROM data 
    WHERE prim_key = x.prim_key and roll_no ='1' 
) starttime , 
    (SELECT data.ts 
    FROM woman_data 
    WHERE prim_key = x.prim_key and roll_no ='10' 

) endtime 

FROM data x 
    INNER JOIN y 
ON x.prim_key = y.prim_key 
) n 
ORDER BY n.prim_key 
+0

謝謝..工作對我來說非常好.. – user1606540

+0

@ user1606540​​:任何時候:) –

相關問題