我正在尝试构建一个基于下面的field_number列创建单独列的查询。查询应按lead_id分组。 form_id是比赛(我需要能够根据我需要统计数据的比赛手动更改form_id)。 field_number每个数字代表我需要创建的列。所以1 =电子邮件,4 =名字,5 =姓氏等等。
对我如何做到这一点的任何帮助表示赞赏。下面我需要从表中获取数据的示例。
+-----+---------+---------+--------------+---------------------------------+
| id | lead_id | form_id | field_number | value |
+-----+---------+---------+--------------+---------------------------------+
| 1 | 1 | 3 | 1 | michael.smith@gmail.com |
| 2 | 1 | 3 | 4 | Michael |
| 3 | 1 | 3 | 5 | Smith |
| 4 | 1 | 3 | 6 | eNewsletter Sign Up Form |
| 5 | 2 | 3 | 1 | jack.johnson@gmail.com |
| 6 | 2 | 3 | 4 | Jack |
| 7 | 2 | 3 | 5 | Johnson |
| 8 | 2 | 3 | 6 | eNewsletter Sign Up Form |
| 9 | 3 | 3 | 1 | bobbie@hotmail.com |
| 10 | 3 | 3 | 4 | Bobbie |
| 11 | 3 | 3 | 5 | DeLeon |
| 12 | 3 | 3 | 6 | eNewsletter Sign Up Form |
| 13 | 4 | 3 | 1 | noname@gmail.com |
| 14 | 4 | 3 | 6 | H&H eNewsletter Sign Up Form |
| 15 | 5 | 3 | 1 | judybyers@hotmail.com |
| 16 | 5 | 3 | 4 | Judy |
| 17 | 5 | 3 | 5 | Byers |
| 18 | 5 | 3 | 6 | eNewsletter Sign Up Form |
| 19 | 6 | 3 | 1 | Andrem@yahoo.com |
| 20 | 6 | 3 | 4 | Andre |
| 21 | 6 | 3 | 5 | M |
| 22 | 6 | 3 | 6 | eNewsletter Sign Up Form |
| 23 | 7 | 3 | 1 | larryl@gmail.ca |
| 24 | 7 | 3 | 4 | Larry |
| 25 | 7 | 3 | 5 | Landerson |
| 26 | 7 | 3 | 6 | eNewsletter Sign Up Form |
| 27 | 8 | 3 | 1 | steph@yahoo.com |
| 28 | 8 | 3 | 4 | Stephanie |
| 29 | 8 | 3 | 6 | eNewsletter Sign Up Form |
答案 0 :(得分:1)
您可以通过聚合执行此操作:
select lead_id, form_id,
max(case when field_number = 1 then value end) as email,
max(case when field_number = 4 then value end) as firstname,
max(case when field_number = 5 then value end) as lastname
from t
where form_id = @form_id
group by lead_id, form_id;
这假设每个字段最多只出现一次lead_id
/ form_id
组合。
答案 1 :(得分:0)
我不了解您对form_id
的要求,但是为了将行中的值转换为列,查询将如下所示(我只做三个作为示例,您可以添加其他值继续添加inner join
条款)
select
t1.lead_id
, t1.value as email
, t4.value as firstName
, t5.value as lastName
from
(
select
lead_id
, value
from
data_table
where
field_number = 1 -- email address
) as t1
, inner join
(
select
lead_id
, value
from
data_table
where
field_number = 4 -- first name
) as t4
on t1.lead_id = t4.lead_id
, inner join
(
select
lead_id
, value
from
data_table
where
field_number = 5 -- last name
) as t5
on t1.lead_id = t5.lead_id