针对先前查询结果的T-SQL查询

时间:2012-09-25 19:42:20

标签: sql sql-server tsql

我很难在互联网上搜索这个,所以我想在这里问T-SQL问题。我有一张名为CUST的桌子。 CUST包含客户入职日期,姓名,公司,地址,电子邮件等。我写了一个简单的查询来根据entrydate找到新客户;

Select * from CUST WHERE ENTRYDATE between '2012-08-01' and '2012-08-30'

除非发现问题,否则效果很好。当我们的网上商店创建新订单时,如果客户详细信息不完全匹配,则会创建新客户。在这种情况下,我想获取原始结果,如果我有多个cust.firstname + cust.lastname + cust.company,则修剪结果集。我可以在单个查询中编写这些,只是不确定如何在单个sql脚本中执行此操作。

我考虑过将名称连接回到表格,虽然连接没有错误,但我不知道如何计算出现次数,我正在考虑计算客户数量。

我的联接看起来像这样(删除了分组依据和列选择,以便于阅读;

from CUST
    Right Outer Join 
    (
    select *
    from CUST 
    WHERE ENTRYDATE between '2012-08-01' and '2012-08-30'
            AND LTRIM(RTRIM(Firstname + Lastname + Company)) <> ''
    Group By *     
    ) as newcs

    on LTRIM(RTRIM(CUST.Firstname + CUST.Lastname + CUST.Company)) = LTRIM(RTRIM(newcs.Firstname + newcs.Lastname + newcs.Company))

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

如果您要删除重复记录,可以使用以下脚本:

DELETE FROM Customer
WHERE PKCol IN 
(    
    SELECT PK_Column FROM 
    ( 
        SELECT ROW_NUMBER() OVER(PARTITION BY FirstName, LastName, Company ORDER BY EntryDate) AS RN, PK_Column
        FROM Customers
    ) A
    WHERE A.RN > 1 
) 

答案 1 :(得分:1)

在本报告期之前未输入的当前时间段内的不同记录:

SELECT DISTINCT c1.*
FROM @CUST c1
WHERE c1.ENTRYDATE BETWEEN '2012-08-01' AND '2012-08-30'
AND NOT EXISTS (SELECT 1 
    FROM @CUST c2 
    WHERE c2.ENTRYDATE < '2012-08-01'
    AND LTRIM(RTRIM(c1.Firstname + c1.Lastname + c1.Company)) = LTRIM(RTRIM(c2.Firstname + c2.Lastname + c2.Company))
)

答案 2 :(得分:0)

此查询仅显示具有不同(裁剪)FirstName + LastName + Company

最新客户
SELECT FirstName,LastName,Company,EntryDate FROM(
    SELECT *, R=ROW_NUMBER() OVER (PARTITION BY ID ORDER BY EntryDate DESC) FROM(
        SELECT FirstName,LastName,Company , EntryDate, ID= LTRIM(RTRIM(FirstName)) + LTRIM(RTRIM(LastName)) + LTRIM(RTRIM(Company))
         FROM CUST
        WHERE EntryDate BETWEEN '2012-08-01' and '2012-08-30'
        ) AS a
    ) AS b
WHERE R=1

如果您需要使用最旧版本,请在DESC条款

后删除ORDER BY部分