关于组合行值的SQL

时间:2017-07-31 14:12:33

标签: mysql sql

我对现有数据库表的SQL语句有疑问:

SELECT * FROM TABLENAME 

使用以下列提供结果:idlead_idfield_numbervalue

ID | LEAD_ID |  FIELD_NUMBER  | VALUE
 1 | 1       | 1              | yes
 2 | 1       | 2              | a@mail.com
 3 | 2       | 1              | yes
 4 | 2       | 2              | b@mail.com
 5 | 3       | 1              | no
 6 | 3       | 2              | c@mail.com

是否可以将value列拆分为两个不同的列?

预期结果:

LEAD_ID | YES_OR_NO | EMAIL
      1 | yes       | a@mail.com
      2 | yes       | b@mail.com
      3 | no        | c@mail.com

我不能正确使用MAX()参数吗?

3 个答案:

答案 0 :(得分:1)

使用SELF JOIN并为每个自联接定义FIELD_NUMBER(如果在示例中使用的不仅仅是两个)。

SELECT t.LEAD_ID, t.value AS YES_OR_NO, sub.VALUE AS EMAIL
FROM TABLENAME t
INNER JOIN TABLENAME sub ON t.LEAD_ID = sub.LEAD_ID AND sub.FIELD_NUMBER !=1 
WHERE t.FIELD_NUMBER = 1

输出

LEAD_ID YES_OR_NO EMAIL
1       yes       a@mail.com
2       yes       b@mail.com
3       no        c@mail.com

SQL小提琴:http://sqlfiddle.com/#!9/1587e3/3/0

答案 1 :(得分:0)

您可以使用自我加入

  select a.LEAD_ID, a.VALUE  as YES_OR_NOT, b.VALUE as EMAIL 
  from TABLENAME a 
  inner  join TABLENAME b on a.LEAD_ID = b.LEAD_ID and b.field_number = 2
  where a.field_number = 1

答案 2 :(得分:-1)

像:

SELECT DISTINCT LEAD_ID
                , CASE WHEN FIELD_NUMBER = 1 THEN VALUE END AS 'YES_OR_NO'
                , CASE WHEN FIELD_NUMBER = 2 THEN VALUE END AS 'EMAIL'
  FROM TABLENAME

无需自我加入