gpt4 book ai didi

SQL重复优化

转载 作者:行者123 更新时间:2023-12-04 13:52:56 25 4
gpt4 key购买 nike

我有以下查询:

原始查询:

SELECT
cd1.cust_number_id, cd1.cust_number_id, cd1.First_Name, cd1.Last_Name
FROM @Customer_Data cd1
inner join @Customer_Data cd2 on
cd1.Cd_Id <> cd2.Cd_Id
and cd2.cust_number_id <> cd1.cust_number_id
and cd2.First_Name = cd1.First_Name
and cd2.Last_Name = cd1.Last_Name
inner join @Customer c1 on c1.Cust_id = cd1.cust_number_id
inner join @Customer c2 on c2.cust_id = cd2.cust_number_id
WHERE c1.cust_number <> c2.cust_number

enter image description here

我优化如下,但是我的优化有错误,找不到:

优化查询:

    SELECT cd1.cust_number_id, cd1.cust_number_id, cd1.First_Name,cd1.Last_Name
FROM (
SELECT cdResult.cust_number_id, cdResult.First_Name,cdResult.Last_Name, COUNT(*) OVER (PARTITION BY cdResult.First_Name, cdResult.Last_Name) as cnt_name_bday
FROM @Customer_Data cdResult
WHERE cdResult.First_Name IS NOT NULL
AND cdResult.Last_Name IS NOT NULL) AS cd1
WHERE cd1.cnt_name_bday > 1;

enter image description here

测试数据:

DECLARE @Customer_Data TABLE
(
Cd_Id INT,
cust_number_id INT,
First_Name NVARCHAR(30),
Last_Name NVARCHAR(30)
)

INSERT @Customer_Data (Cd_Id,cust_number_id,First_Name,Last_Name)
VALUES (1, 22, N'Alex', N'Bor'),
(2, 22, N'Alex', N'Bor'),
(3, 23, N'Alex', N'Bor'),
(4, 24, N'Tom', N'Cruse'),
(5, 25, N'Tom', N'Cruse')

DECLARE @Customer TABLE
(
Cust_id INT,
Cust_number INT
)


INSERT @Customer (Cust_id, Cust_number)
VALUES (22, 022),
(23, 023),
(24, 024),
(25, 025)

问题是原始查询返回 6 行(重复行)。而优化后的返回只是重复,如何让优化后的查询也重复了行?

最佳答案

我建议只使用窗口函数:

SELECT CD.cud_customer_id
FROM (SELECT cd.*, COUNT(*) OVER (PARTITION BY cud_name, cud_birthday) as cnt_name_bday FROM dbo.customer_data cd
) cd
WHERE cnt_name_bday > 1;

您的查询正在查找姓名或生日的重复项。您想要同时使用两者的副本。

关于SQL重复优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52388011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com