【问题标题】:Split data in column based on value of in another column根据另一列中的值拆分列中的数据
【发布时间】:2020-08-14 02:08:53
【问题描述】:

我有一张表,里面装满了从两个不同地方导入的艺术家和曲目标题。

有些在不同列中的 Artist 和 Title 是正确的,但在其他行中,所有内容都在 Title 列中,用“-”分隔,Artist 列是 NULL

在源头更改它不是一种选择,因为两种数据格式都在同一个日志文件中。

我想我需要在 Artist 列中获取所有具有 NULL 值的行,然后使用 STRING_SPLIT 拆分 Title 列。我的数据库是 SQL server 2019。

我尝试在互联网上修改一堆不同的示例,但没有一个能接近工作。

感谢您的帮助!

【问题讨论】:

    标签: sql sql-server sql-server-2019


    【解决方案1】:

    您可以将其作为选择查询来执行:

    select t.*,
           (case when artist is null and title like '%-%'
                 then left(title, charindex('-', title) - 1)
                 else artist
            end) as imputed_artist,
           (case when artist is null and title like '%-%'
                 then stuff(title, 1, charindex('-', title) + 1, '')
                 else title
            end) as imputed_title
    from t;
    

    可以在update 中应用类似的逻辑。

    【讨论】:

    • 感谢 Gordan,效果非常好,我只需将 then left(title, 1, charindex('-', title) - 1) 更改为 then left(title, charindex('-', title) - 1),因为出现错误并更改 ``then stuff(title, 1, charindex('-', title) + 2, '')` 到then stuff(title, 1, charindex('-', title) + 1, '') 因为它切断了第一个字符。请原谅我的基础,但我将如何将其更改为更新?
    • @no_event_logged 。 . .第一个是错字。第二个是对连字符周围有多少空格的误解。我确定了答案。
    猜你喜欢
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2021-06-03
    • 2021-08-23
    相关资源
    最近更新 更多