1

我在使用 SQL 时遇到的问题是,我试图将与 ID 相关联的列中的数据导出到其他 3 列中,但是我最终得到了很多 NULLS 和多个相同的 IDS,如下图所示。

我有一个有 4 列的表,在这些列中数据以一种非常奇怪的方式存储。我的桌子看起来像这样

entry_id| field_id |      value                 | value_ID |
|    480|       -5 |      string of text| 10    |
|    480|      -20 |      string of other text  | 10       | 
|    480|      -23 |      Yes                   | 10       |
|    480|      -22 |      No                    | 10       |

我设计了一个查询,将字段 ID 转换为带有附加值的新列。

查询如下所示:

 SELECT 
 ticket.ticket_id,
 ticket.number,
 users.name,

 CASE WHEN val.field_id IN (5) THEN val.value end as "Issue Summary",
 CASE WHEN val.field_id IN (20) THEN val.value end as "Project Site",
 CASE WHEN val.field_id IN (23) THEN val.value end as "Action"

 FROM ost_ticket ticket

 LEFT JOIN ost_form_entry entry ON (ticket.ticket_id = entry.object_id)
 LEFT JOIN ost_form_entry_values val ON (entry.id = val.entry_id)
 LEFT JOIN ost_user users ON (ticket.user_id = users.id)
 LEFT JOIN ost_form_field fields ON (val.field_id = fields.id)

此查询返回: http: //i.stack.imgur.com/hqBv0.png(由于缺乏声誉,无法嵌入图片。)

如您所见,我有多个相同的票证 ID 和大量 NULL。我应该使用什么查询来让每个唯一的ticket_id 只有一行

4

1 回答 1

0

我猜你想要的是在一行中获取字段值:

SELECT 
 ticket.ticket_id,
 ticket.number,
 users.name,
 issue_sum.value as "Issue Summary",
 project_site.value as "Project Site",
 action.value as "Action"
 FROM ost_ticket ticket
 LEFT JOIN ost_form_entry entry ON (ticket.ticket_id = entry.object_id)
 LEFT JOIN ost_form_entry_values issue_sum 
     ON (entry.id = issue_sum.entry_id) and issue_sum.field_id = 5
 LEFT JOIN ost_form_entry_values project_site 
     ON (entry.id = project_site .entry_id) and project_site.field_id = 20 
 LEFT JOIN ost_form_entry_values action 
     ON (entry.id = action.entry_id) and action.field_id = 23
 LEFT JOIN ost_user users ON (ticket.user_id = users.id)
 LEFT JOIN ost_form_field fields ON (val.field_id = fields.id)

鉴于每张票可以有多个实体记录,我只能建议使用聚合:

  SELECT 
     ticket.ticket_id,
     ticket.number,
     users.name,
     MAX(issue_sum.value) as "Issue Summary",
     MAX(project_site.value) as "Project Site",
     MAX(action.value) as "Action"
     FROM ost_ticket ticket
     LEFT JOIN ost_form_entry entry ON (ticket.ticket_id = entry.object_id)
     LEFT JOIN ost_form_entry_values issue_sum 
         ON (entry.id = issue_sum.entry_id) and issue_sum.field_id = 5
     LEFT JOIN ost_form_entry_values project_site 
         ON (entry.id = project_site .entry_id) and project_site.field_id = 20 
     LEFT JOIN ost_form_entry_values action 
         ON (entry.id = action.entry_id) and action.field_id = 23
     LEFT JOIN ost_user users ON (ticket.user_id = users.id)
     LEFT JOIN ost_form_field fields ON (val.field_id = fields.id)
GROUP BY  
     ticket.ticket_id,
     ticket.number,
     users.name;
于 2014-08-29T09:28:32.730 回答