简体   繁体   中英

Creating a new column in an SQL table and conditionally adding only some content from an existing column

I'm working with iOS backups, and I'd like to split a single column into two columns and then move content from the original column to the new column based on the value of a third column. So any item with 0 in is_from_me below would be moved to a new column text_not_from_me .

I'm using SQLite as the RDBMS.

So this:

text               is_from_me  
--------           ------------      
Hi John!           0
Hi Jane.           1
How are you?       0
Not bad. You?      1

Would become this:

text            text_not_from_me      is_from_me
----------      --------------------  --------------
                 Hi John!             0
Hi Jane.                              1
                 How are you?         0
Not bad. You?                         1

I've tried the following but am getting an error noting that the text_not_from_me column doesn't exist:

SELECT
    datetime (message.date / 1000000000 + strftime ("%s", "2001-01-01"), "unixepoch", "localtime") AS message_date,
    message.text, 
    CASE
        WHEN is_from_me = 1 THEN message.text
        ELSE text_not_from_me
    END AS text_not_from_me,
    message.is_from_me,
    chat.chat_identifier

FROM
    chat
    INNER JOIN chat_message_join ON chat_message_join.chat_id    = chat."ROWID"
    INNER JOIN message           ON chat_message_join.message_id = message."ROWID"

ORDER BY
     message_date ASC;

Isn't this what you want?

CREATE VIEW side_by_side_chat_messages AS

SELECT
    m."date",
    c.chat_identifier,
    CASE WHEN m.is_from_me = 1 THEN m.text END AS text_from_me,
    CASE WHEN m.is_from_me = 0 THEN m.text END AS text_not_from_me,
    m.is_from_me

FROM
    message AS m
    INNER JOIN chat_message_join AS j ON j.chat_id = m."ROWID"
    INNER JOIN chat              AS c ON j.chat_id = c."ROWID"

--ORDER BY
--    m."date"
;

Note that queries in VIEW objects do not have ORDER BY clauses (yes, I agree it's annoying) so it's commented-out. If you want to persist non-trivial ORDER BY logic in a VIEW then use a ROW_NUMBER() ( PARTITION BY x ORDER BY y ) AS orderByThis column in the VIEW and expose it to consumers so they just need to add ORDER BY orderByThis when they query the VIEW .

eg

SELECT
    v.*
FROM
    side_by_side_chat_messages AS v
ORDER BY
    v."date"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM