匹配并比较SQL Server中的两个表

时间:2015-04-24 17:30:57

标签: sql sql-server sql-server-2008 tsql

我需要比较数据库中的两个表。他们存储类似的信息。 但是,在某些情况下IDSegmentSUBSTRING (data, 1, 1))匹配,但每个ID的服务编号和服务日期不同。

这是我的示例数据。在这种情况下,应选择两个突出显示的行:

Example data

我尝试过这样的事情:

SELECT 
    T.ID, 
    SUBSTRING(data, 1, 1) AS Seg, 
    SUBSTRING(data, 2, 4) AS sn, 
    CONVERT(DATE, SUBSTRING(data, 11, 8)), 
    ServiceNumber, ServiceDate
FROM
    P
JOIN 
    T ON p.ID = t.ID
WHERE
    SUBSTRING(data, 1, 1) != Segment
    AND SUBSTRING(data, 2, 4) != ServiceNumber
    AND CONVERT(DATE, SUBSTRING(data, 11, 8)) != ServiceDate;

SQL Fiddle链接在这里:

http://sqlfiddle.com/#!6/d6aee/10

任何想法都会受到欢迎!

3 个答案:

答案 0 :(得分:2)

你想只选择区别吗?

WITH cte AS (
  SELECT ID, 
    CAST(SUBSTRING ( data ,1 , 1 ) AS INT) AS Seg, 
    CAST(LTRIM(SUBSTRING ( data ,2 , 4 )) AS VARCHAR(25)) AS sn, 
    CONVERT(date,SUBSTRING ( data ,11 , 8 )) AS ServiceDate
from P
)
SELECT *
FROM t
WHERE NOT EXISTS (
    SELECT 1 FROM cte c 
    WHERE c.ID = t.ID
    AND c.Seg = t.Segment
    AND c.sn = t.ServiceNumber
    AND c.ServiceDate = t.ServiceDate)

http://sqlfiddle.com/#!6/d6aee/30

答案 1 :(得分:0)

我不完全确定我明白你要做什么,但试试这个。

假设列中的字符数量是一致的。

SELECT T.ID, 
SUBSTRING ( data ,1 , 1 ) AS Seg, 
SUBSTRING ( data ,2 , 4 ) AS sn, 
CONVERT(date,SUBSTRING ( data ,11 , 8 )), ServiceNumber, ServiceDate
FROM T
INNER JOIN P ON T.SERVICENUMBER = SUBSTRING(P.DATA,2,3) 
            AND T.SERVICENUMBER = RIGHT(P.DATA,7)
WHERE P.ID = T.ID

答案 2 :(得分:0)

假设您的粘贴示例中存在错误,即第二行不应突出显示为ID,段和日期相同,您可以通过将编码列分成以下来简化问题它的组件带有CTE或派生表,然后便于比较:

WITH FixedTableP AS
(
     SELECT P.ID,
            SUBSTRING ( [data] ,1 , 1 ) AS PSegment,
            SUBSTRING( [data] ,2 , 4 ) AS PServiceNumber,
            CONVERT(date,SUBSTRING ( data ,11 , 8 )) AS PServiceDate
     FROM P
)
SELECT T.ID, P.ID, T.ServiceNumber, P.PServiceNumber, T.ServiceDate, P.PServiceDate
FROM T
JOIN FixedTableP P ON p.ID=t.ID AND p.PSegment = t.Segment
WHERE P.PServiceDate <> T.ServiceDate 
      AND P.PServiceNumber <> T.ServiceNumber;

SqlFiddle here