需要将所有记录重新排列到相同的行中

时间:2013-05-12 10:55:06

标签: mysql

我需要以下代码才能让所有三个proj1proj4proj5列根据日期分别在一行中。

正如您所看到的,日期相似但它显示在不同的记录中。

enter image description here

MYSQL查询如下:

select DISTINCT dates,proj1,proj4, proj5 from 
    (SELECT DISTINCT tc.dates AS dates , IF( tc.project_id = 1, tc.minutes, '' ) AS 'proj1',
    IF(tc.project_id = 5, tc.minutes, '') AS 'proj5', IF(tc.project_id = 4, tc.minutes, '') AS 'proj4'
FROM timecard AS tc where (tc.dates between '2013-04-01' AND '2013-04-05') ) as X

我需要所有三个proj1proj4proj5记录才能显示所有相同的行,然后查询应该只有5行

2 个答案:

答案 0 :(得分:1)

您可以按dates进行分组,然后使用max()显示非空的值

select dates, max(proj1) as proj1, max(proj4) as proj4, max(proj5) as proj5
from timecard 
where tc.dates between '2013-04-01' AND '2013-04-05'
group by dates

答案 1 :(得分:0)

试试这个sql。

select dates,
        (case t1.proj1
        when t1.proj1 not null then t1.proj1 
        when t2.proj1 not null then t2.proj1
        when t3.proj1 not null then t3.proj1
        end) as "proj1",
        (case t1.proj2
        when t1.proj2 not null then t1.proj2 
        when t2.proj2 not null then t2.proj2
        when t3.proj2 not null then t3.proj2
        end) as "proj2",
        (case t1.proj3
        when t1.proj3 not null then t1.proj3 
        when t2.proj3 not null then t2.proj3
        when t3.proj3 not null then t3.proj3
        end) as "proj3"
from timecard t1,timecardt2,timecardt3
where t1.dates=t2.dates
and t2.dates=t3.dates
group by t1.dates