SQL 查询以获取在数据库中注册但没有电子邮件地址的客户(CS 可以在同一字段中包含电话号码和电子邮件但重复)

SQL Query to fetch the customers registered in the DB without email address(CS can have phonenumber and email in the same field but duplicating)

请帮助我编写此查询, 在数据库中 - 客户注册了两次,一行在 VALUE 字段中使用电子邮件地址,另一行在 SAME VALUE 字段中使用 phone 号码。 我想获取在 VALUE FIELD 中没有电子邮件地址的客户。 例如,我只想从我分享的图中显示的列表中获取最后一行。

感谢您的帮助!

我尝试创建多个 SELECT 查询,但仍然没有获得准确的值。

我建议您使用以下查询,使用确切的列和 table 名称进行修改。我们使用 string_agg 合并同一客户 ID 的所有值字段,并且仅当其中 none 包含 @ 符号时才显示它们。

create table customers(
id int, 
name varchar(25),
value varchar(25));
insert into customers values
(1,'Mr A','1234'),
(1,'Mr A','a@b.c'),
(2,'Mr B','6789');
select
  id,
  max(name) "name",
  string_agg(value,', ')
from
  customers
group by
  id
having 
  string_agg(value,', ')  NOT LIKE '%@%';
id | name | string_agg
-: | :--- | :---------
 2 | Mr B | 6789      

db<>fiddle here

在没有看到 table 模式或示例数据的情况下,我在这里假设您有一个两行共有的字段,因此您知道具有电子邮件值的客户行和具有电子邮件值的客户行phone 值链接到同一客户。出于本示例的目的,我将该字段称为“customer_number”。

我建议使用这样的辅助语句进行查询:

WITH customers_with_emails AS (
  SELECT customer_number
  FROM customers
  WHERE customer_value LIKE '%@%'
)
SELECT *
FROM customers
WHERE customer_number NOT IN (
  SELECT customer_number 
  FROM customers_with_emails
);

这将 return 拥有 phone 号码但没有电子邮件地址的客户。