2014-08-29 78 views
1

我遇到的SQL問題是我試圖將數據從一個鏈接到一個ID的列導出到另外3列,但是最後我得到了許多NULLS和多個相同的IDS,如下圖所示。SQL:數據分成多行

我有一個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」和很多NULLS。我應該使用什麼樣的查詢讓每個獨特TICKET_ID

回答

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; 
+0

而不是3我現在有2列與此查詢。問題摘要仍然與另外兩個分開。 – howdoiholdallthesequeries 2014-08-29 10:07:10

+0

赦免,我的意思是行。我仍然有一個重複的id行。 – howdoiholdallthesequeries 2014-08-29 11:02:31

+0

圖片僅供參考:http://imgur.com/WNQbbFL – howdoiholdallthesequeries 2014-08-29 11:12:31