根据ID将MySql行更改为列

时间:2017-05-11 06:33:22

标签: mysql

我在MySql中有一些数据,它显示为这样的随机顺序:

╔═════════╦══════════════╦═══════════╗
║ lead_id ║ field_number ║   value   ║
╠═════════╬══════════════╬═══════════╣
║    1    ║      1       ║  Richard  ║
║    1    ║      2       ║    CEO    ║
║    1    ║      3       ║  New York ║
║    1    ║      4       ║  02/05/63 ║
║    2    ║      1       ║    John   ║
║    2    ║      2       ║    Staff  ║
║    2    ║      3       ║   London  ║
╚═════════╩══════════════╩═══════════╝

我必须输入什么查询才能使表格更改为此布局:

╔═══════╦═══════╦═══════╦══════════╦════════╗
║lead_id║   1   ║   2   ║     3    ║    4   ║
╠═══════╬═══════╬═══════╬══════════╬════════╣
║   1   ║Richard║  CEO  ║ New York ║02/05/63║
║   2   ║ John  ║ Staff ║  London  ║        ║
║       ║       ║       ║          ║        ║
╚═══════╩═══════╩═══════╩══════════╩════════╝

我试过这段代码

SELECT wn3c_rg_lead_detail.lead_id,
    MAX(CASE WHEN field_number = 1 THEN value END) AS name,
    MAX(CASE WHEN field_number = 2 THEN value END) AS title,
    MAX(CASE WHEN field_number = 3 THEN value END) AS city,
    MAX(CASE WHEN field_number = 4 THEN value END) AS date
   wn3c_rg_lead_detail.field_number,
   wn3c_rg_lead_detail.value
FROM wn3c_rg_lead_detail
GROUP BY wn3c_rg_lead_detail.lead_id
ORDER BY wn3c_rg_lead_detail.lead_id

但是它说它不正确查询..

3 个答案:

答案 0 :(得分:0)

简单的数据透视查询可以生成所需的输出:

SELECT
    lead_id,
    MAX(CASE WHEN field_number = 1 THEN value END) AS name,
    MAX(CASE WHEN field_number = 2 THEN value END) AS title,
    MAX(CASE WHEN field_number = 3 THEN value END) AS city,
    MAX(CASE WHEN field_number = 4 THEN value END) AS date
FROM wn3c_rg_lead_detail
GROUP BY lead_id
ORDER BY lead_id

<强>输出:

enter image description here

在这里演示:

Rextester

答案 1 :(得分:0)

如果数字是真实的,那么你必须编写简单的查询

SELECT lead_id, max(case when field_number=1 THEN value END) as name,
                max(case when field_number=2 THEN value END) as position,
                max(case when field_number=3 THEN value END) as located,
                max(case when field_number=4 THEN value END) as date
FROM `tableName` GROUP BY `lead_id` ORDER BY `lead_id` ASC

答案 2 :(得分:0)

如果每个条目都有namefield_number=1,您还可以使用JOIN

SELECT
    n.lead_id lead_id,
    n.value name,
    t.value title,
    c.value city,
    d.value date
FROM yourTable n
LEFT JOIN yourtable t ON t.lead_id = n.lead_id AND t.field_number = 2
LEFT JOIN yourtable c ON c.lead_id = n.lead_id AND c.field_number = 3
LEFT JOIN yourtable d ON d.lead_id = n.lead_id AND d.field_number = 4
WHERE n.field_number = 1
ORDER BY lead_id ASC