SQL Help. How to line up values on the same row, shift one column up?

时间:2017-08-30 21:02:48

标签: mysql sql group-by case

I am having a problem getting the columns to line up, the start_time is one row above the end_time.

This is my code:

'headerOptions' => [
    'colspan' => '2',
]

This is what I want to get

'headerOptions' => [
    'style' => 'display: none;',
]

2 个答案:

答案 0 :(得分:1)

使用LEAD的窗口功能。在这种情况下,最直接的做法是将当前查询嵌套为已写入,然后在外部查询中应用您的分区。参见:

http://mysqlserverteam.com/mysql-8-0-2-introducing-window-functions/

答案 1 :(得分:0)

架构会有所帮助,但我怀疑驱动表不应该是mydata A,而是ref_val b,因此group by和MAX更有意义。根据实际架构,我可能完全错了:

SELECT  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 ref_val B
      JOIN mydata A 
        ON A.ref_res = B.ref_res    
     WHERE B.COMPANY = 'abc'
     GROUP BY  B.NAME