sql - Rotate columns to rows for joined tables -
i have 2 tables similar shown below (just leaving out fields simplicity).
table lead
:
id | fname | lname | email --------------------------------------------- 1 | john | doe | jd@test.com 2 | mike | johnson | mj@test.com
table leadcustom
:
id | leadid | name | value ------------------------------------------------- 1 | 1 | utm_medium | cpc 2 | 1 | utm_term | fall 3 | 1 | subject | business 4 | 2 | utm_medium | display 5 | 2 | utm_term | summer 6 | 2 | month | may 7 | 2 | color | red
i have database captures leads wide variety of forms have many different form fields. first table gets basic info know on each form. second table captures other forms fields sent on can contain lot of different fields.
what trying do join can grab fields lead
table along utm_medium
, utm_term
leadcustom
table. don't need additional fields if sent over.
desired results :
id | fname | lname | email | utm_medium | utm_term --------------------------------------------------------------------------- 1 | john | doe | jd@test.com | cpc | fall 2 | mike | johnson | mj@test.com | display | summer
only way know grab lead data , each record make more calls leadcustom
data looking know there has me more efficient way of getting data.
i appreciate , not can change way capture data , table formats.
if columns fixed, can group + case + max this:
select fname, lname, email, max(case when name = 'utm_medium' value end) utm_medium, max(case when name = 'utm_term' value end) utm_term lead l join leadcustom c on l.id = c.leadid group fname, lname, email
the case assign value leadcustom table when matches given name, otherwise return null, , max pick take assigned value if exists on null.
you can test in sql fiddle
the other way use pivot operator, syntax more complex -- or @ least more easy me.
Comments
Post a Comment