SQL Server:查找配对记录中的差异

时间:2018-07-11 19:20:52

标签: sql-server

我有一个继承的SQL Server查询:

SELECT
    UPPER(ImportRecord.username) AS username,
    COUNT(*),
    'A'
FROM
    Billing.ImportRecord ImportRecord
GROUP BY
    UPPER(ImportRecord.username)

UNION

SELECT
    UPPER(ImportRecord.username) AS username,
    COUNT(*),
    'B'
FROM
    Billing.ImportRecord ImportRecord
INNER JOIN 
    Personnel.Personnel.Persons Persons ON UPPER(ImportRecord.username) = UPPER(Persons.username)
                                        AND ImportRecord.StartDate BETWEEN Persons.ActualStartDate 
                                        AND ISNULL(Persons.ActualEndDate, GETDATE())
INNER JOIN 
    Billing.UserAccount UserAccount ON Persons.PersonId = UserAccount.BeckmanPersonId
                                    AND ImportRecord.StartDate BETWEEN UserAccount.DateEffective 
                                    AND ISNULL(UserAccount.DateRevoked, GETDATE())
GROUP BY
    UPPER(ImportRecord.username)
ORDER BY
    1, 3, 2;

“ ImportRecord”是一个临时表,其中包含从多个来源收集的使用情况数据。

“ UserAccount”保存有关用户帐单状态的信息。

“人员”掌握有关我们人员的一般信息。

如果幸运的话,此查询会产生结果对:“ A”记录是“原始”传入记录,“ B”是通过人员和计费过滤的传入记录。输出示例如下:

    ABLE    2   A
    ABLE    2   B
    BAKER   7   A
    BAKER   7   B
    CHARLIE 2   A
    CHARLIE 7   B
    DELTA   4   A
    ECHO    4   A
    ECHO    4   B

请注意,CHARLIE的记录为“ B”,而DELTA的记录为“ A”。

目前,我必须手动梳理这些内容以查找差异-可能会有数百条记录。我可以编写一个脚本来搜索具有不相等数字值的单例记录和对。

我的问题:SQL Server中是否有更好的方法来解决此问题?

2 个答案:

答案 0 :(得分:1)

尝试此操作,它将输出只有一个值且第三列不同时的所有字段

SELECT  DISTINCT COLUMN1
        ,COUNT(COLUMN3)
FROM    TABLE1
GROUP BY    COLUMN1
            ,COLUMN2
HAVING   COUNT(COLUMN3) < 2

答案 1 :(得分:0)

尝试以下操作:

WITH output_CTE (username, count, code)  
AS  
(  
    SELECT
       UPPER(ImportRecord.username) AS username,
       COUNT(*),
       'A'
FROM
    Billing.ImportRecord ImportRecord
GROUP BY
         UPPER(ImportRecord.username)
UNION
SELECT
       UPPER(ImportRecord.username) AS username,
       COUNT(*),
       'B'
FROM
     Billing.ImportRecord ImportRecord
     INNER JOIN Personnel.Personnel.Persons Persons
         ON UPPER(ImportRecord.username) = UPPER(Persons.username)
            AND ImportRecord.StartDate BETWEEN Persons.ActualStartDate 
                AND isnull(Persons.ActualEndDate, GETDATE())
     INNER JOIN Billing.UserAccount UserAccount
         ON Persons.PersonId = UserAccount.BeckmanPersonId
            AND ImportRecord.StartDate BETWEEN UserAccount.DateEffective 
                AND isnull(UserAccount.DateRevoked, GETDATE())
GROUP BY
         UPPER(ImportRecord.username)
ORDER BY
         1, 3, 2
)  
SELECT 
*
FROM 
  (Select * from output_CTE where code = 'A') as A
Full outer join 
  Output_CTE as B on B.code = 'B'
Where 
  A.code is null or B.code is null
  Or A.count <> B.count;
GO