简体   繁体   English

如何根据特定列中的存在删除具有空白值的记录? - SQL

[英]How to remove records with blank values based on existence in specific column? - SQL

I want to remove all records with blank values in prev and next - but only for cases where the curr value still exists elsewhere.我想删除prevnext中所有具有空白值的记录 - 但仅适用于curr值仍然存在于其他地方的情况。 For example,例如,

Input:输入:

prev   curr   next   rand_value
       B             1231
       B             323
A      B             3232
       B      C      3233
       D             12313

Output: Output:

prev   curr   next   rand_value
A      B             3232
       B      C      3233
       D             12313

My code so far:到目前为止我的代码:

SELECT * 
FROM my_table
WHERE prev IS NOT NULL
OR next IS NOT NULL
-- but this doesn't catch the final row
-- maybe use something like EXISTS?

You can use NOT EXISTS :您可以使用NOT EXISTS

SELECT t1.* 
FROM tablename t1
WHERE t1.prev IS NOT NULL 
   OR t1.next IS NOT NULL
   OR NOT EXISTS (
        SELECT 1
        FROM tablename t2
        WHERE t2.curr = t1.curr AND (t2.prev IS NOT NULL OR t2.next IS NOT NULL)
      );

See the demo .请参阅演示

each unique rand_value will get a row number 1 to X... ordered by prev, next value.每个唯一的 rand_value 将获得一个行号 1 到 X... 按上一个、下一个值排序。 If both are "NULL" it will get a row_number of 1. Since nulls appear first we have to assign a descending order.如果两者都是“NULL”,它将获得 row_number 1。由于空值首先出现,我们必须分配一个降序。

Perhaps 1 way....也许一种方式....

WITH CTE AS (
SELECT *, row_number() over (partition by rand_value order by prev DESC, next DESC) RN
FROM my_table)

SELECT * FROM CTE WHERE RN =1

Alternative way: Get all that are not null, then get all nulls union...替代方法:获取所有不是 null 的,然后获取所有空联合...

SELECT * 
FROM my_table 
WHERE prev IS NOT NULL
   OR next IS NOT NULL  

UNION ALL

SELECT * 
FROM my_table
WHERE prev IS NULL
  AND next is NULL

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

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