Search code examples
phpmysqlwordpresspivot-tablegravity-forms-plugin

Query a specific value with Pivot Table mySQL


I have searched all over the internet and I have had no luck in finding the answer to my question. I hope this has not specifically been posted yet, but if you can point to where i can find the answer I would appreciate it.

I was able to take the following table data below:

id   lead_id form_id field_number   value
1       1      1        1           Hosker
2       1      1        7           b**********@yahoo.com
3       1      1        6           Hyundai Tournament of Champions
4       1      1        3           Adam Scott
5       1      1        4           Harris English
6       1      1        5           2014-01-02 23:59:47
7       1      1        8           5b409692-e9ed-486e-8d77-7d734f1e023d

And get the result below using this query string:

SELECT id, lead_id, form_id, 
MAX(case when field_number = 1 then value end) username, 
MAX(case when field_number = 7 then value end) email, 
MAX(case when field_number = 6 then value end) tournament_name, 
MAX(case when field_number = 3 then value end) primary_golfer, 
MAX(case when field_number = 4 then value end) backup_golfer, 
MAX(case when field_number = 5 then value end) date, 
MAX(case when field_number = 8 then value end) tournament_id 
FROM `wp_rg_lead_detail` GROUP BY lead_id



id   lead_id form_id field_number   value     value                  value                              value          value            value                      value
 1      1      1        1           Hosker    b**********@yahoo.com  Hyundai Tournament of Champions    Adam Scott    Harris English    2014-01-02 23:59:47    5b409692-e9ed-486e-8d77-7d734f1e023d

I just want that query string to only pull the related data when the value of the tournament_id column equals a specific value. How would I do that?


Solution

  • try this query. I think you can use the HAVING clause.

    SELECT id, lead_id, form_id, 
    MAX(case when field_number = 1 then value end) username, 
    MAX(case when field_number = 7 then value end) email, 
    MAX(case when field_number = 6 then value end) tournament_name, 
    MAX(case when field_number = 3 then value end) primary_golfer, 
    MAX(case when field_number = 4 then value end) backup_golfer, 
    MAX(case when field_number = 5 then value end) date, 
    MAX(case when field_number = 8 then value end) tournament_id 
    FROM `wp_rg_lead_detail` GROUP BY lead_id
    HAVING tournament_id = '5b409692-e9ed-486e-8d77-7d734f1e023d'
    

    sqlFiddle In the sqlFiddle I have sample data for 2 different tournament_id and the HAVING clause is applied so that only values for that tournament_id would be returned, you can try removing the HAVING and see that it returns 2 rows.

    Your Group By is not standard since you're selecting id and form_id as well. I suggest you drop the the id or use MIN(id) or MAX(id) and GROUP BY lead_id,form_id