简体   繁体   English

MSSQL:如果有条件,则使用另一列中的值有条件地填充该列

[英]MSSQL: Conditionally Fill in Column With Value From Another Column If Blank

This is the logic I'm trying to implement: 这是我要实现的逻辑:

If 'new_column' is blank then pull in the value from the 'event' column ... otherwise leave the value as is in 'new_column' 如果'new_column'为空,则从'event'列中提取值...否则,将值保留为'new_column'中的值

I have written it successfully in Python code but am new to SQL. 我已经用Python代码成功编写了它,但对SQL来说是新手。

df_EVENT5_6['new_column'] = np.where(df_EVENT5_6['new_column'] == '', df_EVENT5_6['event'], df_EVENT5_6['new_column'])

How do I translate the above Python code to SQL? 如何将上述Python代码转换为SQL?

This is how you can replace blanks in MSSQL: 这是在MSSQL中替换空白的方法:

SELECT REPLACE(new_column, '', event)
FROM TABLE

If you also want to take care of NULLS then you can add ISNULL in same query: 如果您还想处理NULLS,则可以在同一查询中添加ISNULL:

SELECT REPLACE(ISNULL(new_column, event), '', event)
FROM TABLE

您在寻找coalesce()吗?

select coalesce(new_column, event) as new_column

Assuming you're trying to RETURN the data, you would use a the COALESCE function in a SELECT statement, as seen below: 假设您要返回数据,请在SELECT语句中使用COALESCE函数,如下所示:

select
    [new_column] = coalesce(new_column, event),
    [event] = event
from
    df_EVENT;

What COALESCE does is take arguments in order of precedence and returns the first value that is NOT NULL. COALESCE的作用是按优先级顺序接受参数,并返回第一个非NOT值。 Underneath this function it is evaluated as a CASE expression, so you could amend the above for NULL with your condition for Empty-Length strings as such: 在此函数下,它被评估为CASE表达式,因此您可以将空长度字符串的条件修改为NULL,例如:

select
    [new_column] = case when new_column > '' then new_column else event end
    [event] = event
from
    df_EVENT;

This is without knowing your data source. 这是不知道您的数据源的情况。 If you are doing an INSERT from Python, then you could keep your Python logic and apply it to the SQL statement that is passed. 如果您要通过Python执行INSERT,则可以保留Python逻辑并将其应用于所传递的SQL语句。 Otherwise, you could do as I listed above. 否则,您可以按照上面列出的方法进行操作。

Try this if you using Sql server 如果使用Sql server,请尝试此操作

Insert into TABLENAME (Column1)
(Select ISNULL(new_column, eventcolumn) from TABLENAME)

ISNULL function check thats if new_column is null then takes value of eventcolum else take new column value ISNULL函数检查如果new_column为null,则采用eventcolum的值,否则采用新的列值

Or You also can use case when facility of sql. 或者您也可以在使用sql工具时使用大小写。 Case when syntax like this : 语法如下所示的情况:

Select case when isnull(new_column,'') = '' Then eventcolumn else new_column end 当isull(new_column,'')=''时选择大小写,然后eventcolumn否则new_column结束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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