使用CASE将值与用户ID对齐

时间:2014-09-23 21:23:45

标签: mysql sql

我有一个表,它是一个存在名称值对的自定义数据表。以下是此表中某些个人自定义数据的示例:

table custom_data
    user_id | custom_data_name | custom_data_value
    123 | initial contact date | 2014-01-01
    123 | subscription start date | 2014-02-02
    123 | favorite fruit | pears

我想创建一个在个人级别解析这个问题的查询,这样我就能像这样并排查看数据:

user_id | initial_contact_date | subscription_start_date
123 | 2014-01-01 | 2014-02-02

我试过了:

SELECT 
        user_id,
        CASE WHEN base1.custom_data_name = 'initial contact date' THEN custom_data.data END AS initial_contact_date,
        CASE WHEN base1.custom_data_name = 'subscription start date' THEN custom_data.data END AS subscription_start_date
    FROM
        (
        SELECT * FROM custom_data
        WHERE custom_data_name = 'initial contact date' OR custom_data_name = 'subscription start date') base1
    GROUP BY user_id

但我很难解释结果。结果显示,对于每个用户,EITHER initial_contact_date或subscription_start_date的值在一条记录中不能同时存在。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT 
  user_id,
  MAX(CASE WHEN custom_data_name = 'initial contact date' THEN custom_data_value END) AS initial_contact_date,
  MAX(CASE WHEN custom_data_name = 'subscription start date' THEN custom_data_value END) AS subscription_start_date
  --MAX(CASE WHEN custom_data_name = 'favorite fruit' THEN custom_data_value END) AS favorite_fruit 
FROM custom_data
GROUP BY user_id

Sample SQL Fiddle

答案 1 :(得分:2)

您需要汇总数据

select user_id
     , min(case 
             when custom_data_name = 'initial contact date' then custom_data_value
           end) initialContactDate
     , min(case 
             when custom_data_name = 'subscription start date' then custom_data_value
           end) subscriptionStartDate

  from (
    select '123' user_id, 'initial contact date' custom_data_name, '2014-01-01' custom_data_value union all
    select '123' user_id, 'subscription start date' custom_data_name, '2014-01-02' custom_data_value union all
    select '123' user_id, 'favorite fruit' custom_data_name, 'pears' custom_data_value
  ) tt
 group by user_id

USER_ID     INITIALCONTACTDATE  SUBSCRIPTIONSTARTDATE
-----------------------------------------------------
    123             2014-01-01             2014-01-02

SQLFiddle