将列数据合并为一行

时间:2014-05-02 15:29:22

标签: php mysql

我有查询返回以下结果 查询:

SELECT 
    c.meetings_id, c.speakers_id, c.date_sent, c.check_type_id
from
    cf_checkings c
where
    c.void = '0'

结果:

 Meeting_id | Speaker_id | Date_sent | check_type_id
    33  4   2014-02-27  1
    34  200 2014-01-27  1
    34  200 2014-02-20  2
    35  30  2014-01-30  1
    35  30  2014-02-20  2
    35  31  2014-01-30  1
    35  31  2014-02-20  2 
   * 35 31  2014-02-22  2 *

我想要以下结果

Meeting_id | Speaker_id | Date_sent_1 | Date_sent_2
33              4         2014-02-27     
34             200        2014-01-27    2014-02-20
35             30         2014-01-30    2014-02-20 
35             31         2014-01-30    2014-02-22 

任何人都可以提供帮助吗? * /当结果有两行具有相同的meeting_id,speaker_id和check_type_id时,请选择max date_sent

我必须在查询本身执行操作,这是我的限制。 * /

1 个答案:

答案 0 :(得分:1)

您可以使用MIN,MAXCASE Date_sent_2来检查它是否等于date_sent的最小值,然后显示为空

SELECT 
    c.meeting_id, 
    c.speaker_id,
    MIN(c.date_sent) Date_sent_1 , 
    (CASE WHEN MIN(c.date_sent) =MAX(c.date_sent)
    THEN NULL 
    ELSE MAX(c.date_sent)
    END) Date_sent_2 
  FROM 
        mf_checking  c
    WHERE c.void = '0' /* your where criteria */
    GROUP BY c.meeting_id, c.speaker_id

Fiddle Demo

从评论中修改您还可以使用带有最大功能的案例来选择属于check_type_id 1或2的日期

SELECT 
    c.meeting_id,
    c.speaker_id,
    MAX(CASE WHEN c.check_type_id =1 
    THEN c.Date_sent END) Date_sent_1
    ,
    MAX(CASE WHEN c.check_type_id =2 
    THEN c.Date_sent END) Date_sent_2
FROM
        mf_checking   c
    WHERE c.void = '0' /* your where criteria */
    GROUP BY c.meeting_id, c.speaker_id

Fiddle Demo 2