使用数据透视表 mySQL 查询特定值



我在网上搜索了所有内容,但没有找到问题的答案。我希望这还没有专门发布,但如果你能指出我在哪里可以找到答案,我将不胜感激。

我能够获取下表数据如下:

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

并使用此查询字符串获取以下结果:

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

我只希望该查询字符串仅在tournament_id列的值等于特定值时才拉取相关数据。我该怎么做?

尝试此查询。我认为您可以使用HAVING条款。

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 在 sqlFiddle 中,我有 2 种不同tournament_id的示例数据,并应用 HAVING 子句,以便仅返回该tournament_id的值,您可以尝试删除 HAVING 并看到它返回 2 行。

您的分组依据不是标准的,因为您也选择 id 和form_id。我建议你去掉id或使用MIN(id)或MAX(id)并GROUP BY lead_id,form_id

如果我

明白你在问什么,请尝试:

SELECT * FROM TABLE_NAME
WHERE tournament_id = specific_value;

相关内容

  • 没有找到相关文章

最新更新