简体   繁体   English

具有多个条件的 PG SQL 案例 - 编写语句的更简单方法?

[英]PG SQL case when with multiple conditions - simplier way to write statement?

I'm doing a query like so:我正在做这样的查询:

SELECT a.col_1,
       a.col_2,
       a.col_3, 
       a.col_4,
       CASE WHEN b.col_1 is null and b.col_2 is null and b.col_3 is null then 0 else 1 end as fraud
FROM table_a a
LEFT JOIN table_b b
on a.col_1 = b.col_1 and a.col_2 = b.col_2 and a.col_3 = b.col_3 

is there a simplier way to write the case when statement here?有没有更简单的方法来写 case when 在这里声明? I don't want to have to write so many conditions.我不想写这么多条件。 hoping for a better way to streamline this.希望有更好的方法来简化这一点。

You join the tables on equality of the three columns.您加入关于三列相等的表。 If one of the columns is null in either table, the row in question wont get joined.如果任一表中的一列为空,则相关行将不会被连接。 This means, if you see a null in any of the table_b columns in your joined rows, then you do this because you are looking at an outer joined row where all b columns are set to null.这意味着,如果您在连接行的任何 table_b 列中看到 null,那么您这样做是因为您正在查看所有 b 列都设置为 null 的外部连接行。 In other words, if b.col_1 is null, then so are b.col_2, b.col_3 and any other b column.换句话说,如果 b.col_1 为空,那么 b.col_2、b.col_3 和任何其他 b 列也是如此。

Hence:因此:

SELECT a.col_1,
       a.col_2,
       a.col_3, 
       a.col_4,
       CASE WHEN b.col_1 is null then 0 else 1 end as fraud
FROM table_a a
LEFT JOIN table_b b on a.col_1 = b.col_1
                   and a.col_2 = b.col_2
                   and a.col_3 = b.col_3;

You can use num_nulls()您可以使用num_nulls()

num_nulls(col_1, col_2, col_3) > 0 as is_fraud

The above results in a boolean true/false value, not a and integer with 0/1 .上面的结果是一个布尔true/false值,而不是一个 0/​​1 的0/1 If you really want an integer instead of a boolean you can still wrap the result of num_nulls() into a CASE expression.如果您真的想要一个整数而不是boolean ,您仍然可以将num_nulls()的结果包装到 CASE 表达式中。

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

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