0

我有以下查询结果

SELECT DISTINCT user_id, 
                IF(ra.status = 1, created_datetime, 'No record') AS ACTIVATED, 
                IF(ra.status = 0, created_datetime, 'No record') AS DE_ACTIVATED 
FROM   accounts ra 
WHERE  user_id IN ( 12345678 ); 

+----------+---------------------+---------------------+
| user_id  | ACTIVATED           | DE_ACTIVATED        |
+----------+---------------------+---------------------+
| 12345678 | No record           | 2013-04-28 02:32:36 |
| 12345678 | 2013-03-28 02:32:36 | No record           |
+----------+---------------------+---------------------+

我试图只有 1 行记录,结合激活和停用。基本上,让它像这样。

+----------+---------------------+---------------------+
| user_id  | ACTIVATED           | DE_ACTIVATED        |
+----------+---------------------+---------------------+
| 12345678 | 2013-03-28 02:32:36 | 2013-04-28 02:32:36 |
+----------+---------------------+---------------------+

非常感谢任何帮助,因为我建立了我的查询忍者技能。

问候

4

1 回答 1

1

MAX两个条件中的 ,但使“假”条件评估为null。然后将其包装起来,COALESCE因此如果 calcualtedMAX为 null ,它将被替换为no record

SELECT user_id,
  COALESCE(MAX(IF(ra.status = 1, created_datetime, null)), 'No record') AS Activated,
  COALESCE(MAX(IF(ra.status = 0, created_datetime, null)), 'No record') AS Deactivated
FROM accounts ra
WHERE user_id IN (12345678)

如果您要查询多个用户,请将其添加到末尾:

GROUP BY user_id
于 2013-04-26T02:56:08.817 回答