通过将查询结果连接到子查询来检查数据质量,方法是将查询中的测试数据与union all结合使用

时间:2018-09-05 19:30:09

标签: sql

我正在检查数据质量。我们想检查用户通过在子查询中形成的名字来提供给我们的名字的列表,因为我们没有创建表或临时表的权限,因为它是第三方数据库。我可以将列表快速合并到电子表格公式中。我该如何正确地联接到查询结果,以查找是否缺少任何内容。这也是一个很好的示例,说明了如何在脚本中包括测试数据而不创建测试表或临时表! 版本SQL Server 2008 R

--table to check for data quality

SELECT LAST_NAME, FIRST_NAME, PEOPLE_CODE_ID FROM 
test.DBO.PEOPLE WHERE
last_name = 'Berd' and first_name = 'Alivia' OR
last_name = 'Arny' and first_name = 'Jase' OR
last_name = 'Barny' and first_name = 'Cale'
AS A

right join --list from user
        (
select 'Abbie' as first_name, 'Bail' as last_name
UNION select 'Jenny' as first_name, 'Bleee' as last_name
UNION select 'Jase' as first_name, 'Arny' as last_name
UNION select 'Jason' as first_name, 'Bussey' as last_name
) AS B
WHERE A.LAST_NAME = B.LAST_NAME
AND A.FIRST_NAME = B.FIRST_NAME

2 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解您的问题,但是听起来您想将people表与用户列表进行比较,然后返回不在该列表中的用户?

如果是这样,这是使用not exists的一种选择:

with userstosearch as (
    select 'Abbie' as first_name, 'Bail' as last_name
    union all select 'Jenny', 'Bleee' 
    union all select 'Jase', 'Arny' 
    union all select 'Jason', 'Bussey'
) 
select u.* 
from userstosearch u
where not exists (
    select 1
    from test.DBO.PEOPLE p
    where u.firstname = p.firstname and u.lastname = p.lastname
)

如果您更喜欢使用outer join

...
select u.* 
from userstosearch u
    left join test.DBO.PEOPLE p on u.firstname = p.firstname and u.lastname = p.lastname
where p.firstname is null

答案 1 :(得分:0)

如果要查找不匹配的行:

SELECT A.LAST_NAME, A.FIRST_NAME, PEOPLE_CODE_ID
FROM  test.DBO.PEOPLE AS A  

right join --list from user
        (
select 'Abbie' as first_name, 'Bail' as last_name
UNION select 'Jenny' as first_name, 'Bleee' as last_name
UNION select 'Jase' as first_name, 'Arny' as last_name
UNION select 'Jason' as first_name, 'Bussey' as last_name
) AS B ON  A.LAST_NAME = B.LAST_NAME AND A.FIRST_NAME = B.FIRST_NAME


WHERE (A.last_name = 'Berd' and A.first_name = 'Alivia')
    OR (A.last_name = 'Arny' and A.first_name = 'Jase')
    OR (A.last_name = 'Barny' and A.first_name = 'Cale')
AND B.LAST_NAME IS NULL

将匹配的行更改为IS NOT NULL或使用类似的

CASE WHEN B.last_name IS NULL THEN 0 ELSE 1 END AS HasMatch