0

I have a table which is a huge list of all the information that was filled into a form. Each form entry put all the information into the same column, with another column for field_id (and this lets me know exactly where the information was entered). So if the form had 8 entry fields, all the info that was entered would be in one column, and the field_id corresponding to the field it was entered into is in another field.

I am now rebuilding the db to make this mess of a system more useful, but I need to keep all the previously entered data. How can I combine the information from the 8 rows where information was entered into a single row in the new table, based on the field_id column?

So if name/address/phone/email/fax/mother/father/pet were the columns of the new table, but the info for each of these was stored in a single column in the original table with field_ids 1 to 8 in another column, how could I go about doing this?

EDIT: Clearer

Table1 structure: id/meta_value/field_id/entry_id/created_date

Table2 structure: id/name/address/phone/email/fax/mother/father/pet

4

2 回答 2

2

您可以使用MAX和来做到这一点CASE。不知道你的表结构,我只是给你一个例子:

SELECT id,
   MAX(CASE WHEN field_id = 1 THEN meta_value END) 'Name',
   MAX(CASE WHEN field_id = 2 THEN meta_value END) 'Address',
   MAX(CASE WHEN field_id = 3 THEN meta_value END) 'Phone',
   ...
FROM YourTable
GROUP BY id

这会将PIVOT您的结果放入具有多列的单行中。

于 2013-05-30T17:51:26.877 回答
1

好吧,如果我理解正确,您可以执行以下操作:

select
    id,
    (select meta_value from Table1 t2 where field_id = 1 and t2.id = t1.id) as name,
    (select meta_value from Table1 t2 where field_id = 2 and t2.id = t1.id) as address,
    ...
    (select meta_value from Table1 t2 where field_id = 8 and t2.id = t1.id) as pet
from Table1 t1
group by id
于 2013-05-30T17:52:00.017 回答