sql - 如何过滤表以仅检索每条记录的一次出现

标签 sql ssms

我试图为每个客户只查找一次出现的情况。

但是,在我的数据库中,我的客户已添加两次(在 ERP 迁移之后)

目前,

如果我尝试查找出现两次的客户,我必须保留“customer_id”列中具有“C”的客户

在此示例中,“Manu Johns”出现了 2 次,因此我们必须保留最终表中 customer_id 列中具有“C”的那个。

如果我只找到该客户的一次出现。但是,customer_id 列中没有“C”。我们必须按原样将其添加到最终表中

在此示例中,我们有“Mathieu Wainers”,只有当我们将其保留在决赛 table 中时才会出现

哪个查询可以让我得到这个结果:https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=9484f43c0a6c1ccdae7d659ca53e1eab

CREATE TABLE PersonsInitial (
    tel int,
    firstname varchar(255),
    lastname varchar(255),
    Customer_ID varchar(255)
);
insert into PersonsInitial(tel,firstname,lastname,Customer_ID) values
('01234','Manu','Johns','456'),
('01234','Manu','Johns','C456'),
('21234','Fernand','Wajk','C389'),
('13554','Mathieu','Wainers','4683');

select distinct tel, firstname, lastname, customer_id from PersonsInitial

--if there is a person with the same tel number chose the customer id with 'C'
--if I don't have the choice add the customer without C

CREATE TABLE PersonsFinal (
    tel int,
    firstname varchar(255),
    lastname varchar(255),
    Customer_ID varchar(255)
);
insert into PersonsFinal(tel,firstname,lastname,Customer_ID) values
('01234','Manu','Johns','C456'),
('21234','Fernand','Wajk','C389'),
('13554','Mathieu','Wainers','4683');

select distinct tel, firstname, lastname, customer_id from PersonsFinal

最佳答案

您可以根据客户 ID 中是否有“C”将它们排名第一。这就是 cte 存在的原因。

with cte as (select row_number() over (partition by tel, firstname, lastname order by case when left(customer_id, 1) = 'C' then 0 else 1 end) rn, 
                    p.* 
               from PersonsInitial p)
select *
  from cte 
 where rn = 1; <-- selects only those with "C" or those for that there is no "C" lines

dbfiddle

关于sql - 如何过滤表以仅检索每条记录的一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71223396/

相关文章:

SQL 分组依据和交叉应用

keyboard-shortcuts - 在 SQL Management Studio 中更改 "Available databases"的键盘快捷键

sql-server - 如何在 SQL Server Management Studio 编辑器中搜索 ', ' 并替换为 ', ' <CR><LF>

javascript - 获取 SQL 表值的最有效方法是什么?

MySQL 在一个查询中从多个表中删除

mysql - 将 SQL 语句中的 NOT IN 替换为 LEFT JOIN

sql-server - 消息102,级别15,状态1,第3行带有sp_executesql的 ' '附近的语法不正确

sql - 如何查看SQL存储过程的运行进度?

sql-server-2008 - SQL Server Management Studio(或 SQL Server)是否评估 *all* 表达式?

mysql - 导入MySQL中的csv