简体   繁体   English

根据 2 个条件在 SQL 添加新列

[英]Add new column in SQL based on 2 conditions

I would like to create a new column in SQL using two conditions.我想使用两个条件在 SQL 中创建一个新列。 I want to create a column that says 1 if the item count is greater than 1 and if item/sum is greater than 5, otherwise return 0. This is not my original data, is there anyway I could add this new column with these specified rows using a select statement.我想创建一个列,如果项目计数大于 1 并且如果项目/总和大于 5,则返回 0。这不是我的原始数据,无论如何我可以添加这个指定的新列使用 select 语句的行。

First I want to say that using SQL key words or SQL function names as table name or column name should be avoided, so if possible, I recommend to rename the columns "number" and "sum".首先我想说的是,应该避免使用 SQL 关键字或 SQL function 名称作为表名或列名,因此如果可能的话,我建议将列重命名为“number”和“sum”。 The second point is it's unclear what should happen in case the sum column is 0. Since a division by zero is not possible, you will need to add a condition for that.第二点是不清楚如果总和列为 0 会发生什么。由于不可能被零除,因此您需要为此添加一个条件。 Anyway, the way to achieve such things is using CASE WHEN .无论如何,实现这些事情的方法是使用CASE WHEN So let's add the new column:所以让我们添加新列:

ALTER TABLE yourtable ADD column column_name INT;

Now, you need to execute an update command for that column providing the logic you want to apply.现在,您需要对该列执行更新命令,提供您要应用的逻辑。 As an example, you can do this:例如,您可以这样做:

UPDATE yourtable SET column_name =
CASE WHEN item <= 1 THEN 0
WHEN sum = 0 THEN 1
WHEN item / sum > 0.5 THEN 1
ELSE 0 END;

This will set the new column to 1 only in case item is > 1 and sum is 0 or sum item / sum is > 0.5 (greater 50%).只有在 item > 1 且 sum 为 0 或 sum item / sum > 0.5(大于 50%)的情况下,这才会将新列设置为 1。 In all other cases it will be set to 0. Again, the bad column naming can be seen since "WHEN sum..." looks like you really build a sum and not just use a column.在所有其他情况下,它将被设置为 0。同样,可以看到错误的列命名,因为“WHEN sum...”看起来你真的建立了一个总和,而不仅仅是使用一个列。 If you want as example to set the new column to 0 instead of 1 when the sum is 0, just change it and try out.例如,如果您想在总和为 0 时将新列设置为 0 而不是 1,只需更改它并尝试。 In case you want to automatically apply this logic fur future inserts or updates, you can add a trigger on your new column.如果您想在未来的插入或更新中自动应用此逻辑,您可以在新列上添加触发器。 Something like this:是这样的:

CREATE TRIGGER set_column_name
BEFORE INSERT ON yourtable
FOR EACH ROW
SET new.column_name = CASE WHEN new.item <= 1 THEN 0
WHEN new.sum = 0 THEN 1
WHEN new.item / new.sum > 0.5 THEN 1
ELSE 0 END;

But take care, the syntax of triggers depend on the DB you are using (this example will work in MYSQL).但请注意,触发器的语法取决于您使用的数据库(此示例适用于 MYSQL)。 Since you did not tell us which DB you use, you maybe need to modify it.由于您没有告诉我们您使用的是哪个数据库,您可能需要修改它。 Furthermore, depending on your DB type and your requirements, you need zero, one or two triggers (for updates and for inserts).此外,根据您的数据库类型和要求,您需要零个、一个或两个触发器(用于更新和插入)。

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

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