如何根据mysql中的行值拆分列?

时间:2013-03-30 05:37:06

标签: mysql sql conditional-statements

我需要一个来自行值的列。

我有两张桌子。

表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
)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

IMO你应该在应用程序而不是SQL

中执行此操作