1

次のようにSQLステートメントの結果をフォーマットするものはありますか........

TABLE1  
ID ticket_number  
1   2001  
2   2002  

Table2  
tn    name                 create_time  
2001  sms_to_customer      2013-05-05 10:10:19  
2001  sms_to_officer1      2013-05-05 11:17:01  
2001  sms_to_officer2      2013-05-05 12:14:05  
2002  sms_to_officer1      2013-05-05 09:17:01  
2002  sms_to_officer2      2013-05-05 09:30:05  

みたいな結果が欲しい…………

ticket_number   sms_to_customer      sms_to_officer1        sms_to_officer2  
2001            2013-05-05 10:10:19  2013-05-05 11:17:01    2013-05-05 12:14:05  
2002            NA                   2013-05-05 09:17:01    2013-05-05 09:30:05 
4

2 に答える 2

3

nameこれらが の列の値のみである場合はTable2、この静的バージョンのクエリを使用できます。

SELECT  tn,
        COALESCE(MAX(CASE WHEN Name = 'sms_to_customer' THEN Create_Time END), 'NA') `sms_to_customer`,
        COALESCE(MAX(CASE WHEN Name = 'sms_to_officer1' THEN Create_Time END), 'NA') `sms_to_officer1`,
        COALESCE(MAX(CASE WHEN Name = 'sms_to_officer2' THEN Create_Time END), 'NA') `sms_to_officer2`
FROM    Table2
GROUP   BY tn

それ以外の値がある場合は動的 SQLを使用します。

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'COALESCE(MAX(case when Name = ''',
      Name,
      ''' then create_time end), ''NA'') AS ',
      CONCAT('`',Name,'`')
    )
  ) INTO @sql
FROM Table2;

SET @sql = CONCAT('SELECT  tn, ', @sql, ' 
                   FROM Table2
                   GROUP BY tn');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

出力

╔══════╦═════════════════════╦═════════════════════╦═════════════════════╗
║  TN  ║   SMS_TO_CUSTOMER   ║   SMS_TO_OFFICER1   ║   SMS_TO_OFFICER2   ║
╠══════╬═════════════════════╬═════════════════════╬═════════════════════╣
║ 2001 ║ 2013-05-05 10:10:19 ║ 2013-05-05 11:17:01 ║ 2013-05-05 12:14:05 ║
║ 2002 ║ NA                  ║ 2013-05-05 09:17:01 ║ 2013-05-05 09:30:05 ║
╚══════╩═════════════════════╩═════════════════════╩═════════════════════╝
于 2013-04-05T05:58:56.647 に答える
1
SELECT
   ticket_number, t2.create_time as `sms_to_customer`,t3.create_time as `sms_to_officer1`,t4.create_time as `sms_to_officer2` 
  from Table1 t1 
    left join Table2 t2 on (t1.ticket_number=t2.tn and t2.name='sms_to_customer') 
    left join Table2 t3 on (t1.ticket_number=t3.tn and t3.name='sms_to_officer1') 
    left join Table2 t4 on (t1.ticket_number=t4.tn and t4.name='sms_to_officer2');
于 2013-04-05T06:09:04.350 に答える