SQL逻辑:查找具有相似行的非重复

时间:2016-03-28 13:33:12

标签: sql sql-server database sql-server-2012

我会尽力总结我遇到的问题。直到最近我才使用过很多SQL。

目前我正在使用SQL Server 2012,其任务是尝试在SQL表中查找奇怪的内容。具体而言,表包含有关服务器的类似信息。有点meta,我知道。因此,他们每个人共享一个名为" DB_NAME"的列。之后,没有类似的列。因此,我需要比较表A和表B,并生成一个记录列表(服务器),其中服务器未在表A和B中列出。此外,此查询正在针对例外列表运行。我不能100%确定最好地处理这个问题的逻辑。虽然我很想得到一些非常高效的东西,但我更喜欢看到那些目前普通的东西。

SELECT  *
FROM    (SELECT
            UPPER(ta.DB_NAME) AS [DB_Name]
        FROM
            [CMS].[dbo].[TABLE_A] AS ta
        UNION
        SELECT
            UPPER(tb.DB_NAME) AS [DB_Name]
        FROM
            [CMS].[dbo].[TABLE_B] as tb
        ) AS SQLresults
WHERE NOT EXISTS (
    SELECT *
    FROM
        [CMS].[dbo].[TABLE_C_EXCEPTIONS] as tc
    WHERE
        SQLresults.[DB_Name] = tc.DB_NAME)
ORDER BY    SQLresults.[DB_Name]

2 个答案:

答案 0 :(得分:1)

一种方法使用union all和聚合:

select ab.*
from ((select upper(name) as name, 'A' as which
       from CMS.dbo.TABLE_A
      ) union all
      (select upper(name), 'B' as which
       from CMS.dbo.TABLE_B
      )
     ) ab
where not exists (select 1
                  from CMS.dbo.TABLE_C_EXCEPTION e
                  where upper(e.name) = ab.name
                 )
having count(distinct which) <> 2;

默认情况下,SQL Server不区分大小写。我在查询中留下了upper(),以防您的安装区分大小写。

答案 1 :(得分:0)

这是使用EXCEPT的另一个选项。我在联盟的每一半都添加了一个组,因为在您的原始帖子中,如果DB_NAME在您的表中是唯一的,则不清楚。

select DatabaseName
from
(
    SELECT UPPER(ta.DB_NAME) AS DatabaseName
    FROM [CMS].[dbo].[TABLE_A] AS ta
    GROUP BY UPPER(ta.DB_NAME)

    UNION ALL

    SELECT UPPER(tb.DB_NAME) AS DatabaseName
    FROM [CMS].[dbo].[TABLE_B] as tb
    GROUP BY UPPER(tb.DB_NAME) 
) x
group by DatabaseName
having count(*) < 2
EXCEPT
(
    select DN_Name 
    from CMS.dbo.TABLE_C_EXCEPTION
)