2013-03-30 76 views
0

我需要從行值的列。如何根據mysql中的行值拆分列?

我有兩張桌子。

表1:working_day包含所有工作日的日期列表。

date 
-------- 
2013-03-30 
2013-03-29 
2013-03-28 

表2:條目包含進出時間每個員工。

id In Out Date 
1 9 0 2013-03-30 
2 8 0 2013-03-30 
3 7 0 2013-03-30 
1 8 18 2013-03-29 
2 9 16 2013-03-29 
3 6 20 2013-03-29 
4 12 15 2013-03-29 

預期輸出:

ID 29-03-2013_IN 29-03-2013_Out 30-03-2013_In 
1 8     18   9 
2 9     16   8 
3 6     20   7 
4 12     15   0 

嘗試:

SELECT id, 
Case condition1 for 29_in, // I don't know which condition suite here. 
Case condition1 for 29_out, 
Case condition1 for 30_in 
FROM entry 
WHERE DATE 
IN (
SELECT * 
FROM (
SELECT DATE 
FROM working_day 
ORDER BY DATE DESC 
LIMIT 0 , 2 
)a 
) 
+0

聽起來像是你需要一個group by子句,這將讓你你需要,只是沒有在你指定的格式的結果。 – starshine531

+1

這篇文章有一個很好的howto在MySQL中進行數據透視:http://www.artfulsoftware.com/infotree/qrytip.php?id=78 – koriander

回答

2

你可以嘗試這樣的事情:

select 
    e.id, 
    (SELECT `in` FROM entry WHERE id = e.id AND date = '2013-03-30') as '2013-03-30_in', 
    (SELECT `in` FROM entry WHERE id = e.id AND date = '2013-03-29') as '2013-03-29_in', 
    (SELECT `out` FROM entry WHERE id = e.id AND date = '2013-03-29') as '2013-03-29_out' 
from entry e 
group by e.id; 

這裏是Demo

+0

+1 for fiddle Demo – Dhinakar

0

IMO你應該這樣做,在應用程序而不是SQL