如何使该sql视图显示数据差异

时间:2015-01-28 09:21:13

标签: sql sql-server tsql view

最近我准备编辑我的数据库的历史记录。我做了一个表,在更新之前和之后保存记录。我将列添加到历史表中,该表将2个记录(更新前后的记录)配对。所以我有完整的历史表。

我现在要做的是创建复杂的(在我看来)视图。我想显示该表中所有记录之间的所有差异。让我解释一下。

我在该表中有20列,但让我们用4来表示我的意思: 题名/作者/日期/ PairIndex。这些是列名。

数据:

Book1/Author1/30-03-1990/1
Book1/Author1/30-04-1990/1
Book2/Author2/30-03-2004/2
Book3/Author3/30-03-2004/2

这里我有2个更新。第一次更新只是日期变更。第二次更新改变了书名和作者。我希望在我的观点中显示如下内容:

1-- 30-03-1990 -- 30-04-1990
2-- Book2 -- Book3
2-- Author2 -- Author3

所以每个差异都有自己的行,数据不同。这使得每对记录都具有相同的PairIndex。

这是我的工作代码:

Create table Boom ( Book   VARCHAR(10),
                             author VARCHAR(10),
                             date     DATE,
                             id     INT )

INSERT INTO Boom
VALUES ( 'Book1', 'Author1', '19900330', 1 ),
       ( 'Book1', 'Author1', '19900430', 1 ),
       ( 'Book2', 'Author2', '20040330', 2 ),
       ( 'Book3', 'Author3', '20040330', 2 );

WITH cte
AS (
      SELECT Boom.*, ROW_NUMBER() over (partition by ID order by author) as RN
      FROM Boom
   ) 

select b1.id, b2.id, b1.date, b2.date
  from cte b1 
  join cte b2 
    on b1.id = b2.id 
   and b1.rn < b2.rn 
   and b1.date <> b2.date

select b1.id, b2.id, b1.author, b2.author
  from cte b1 
  join cte b2 
    on b1.id = b2.id 
   and b1.rn < b2.rn 
   and b1.author<> b2.author

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

DECLARE @SomeData AS TABLE ( Book   VARCHAR(10),
                             Author VARCHAR(10),
                             Dt     DATE,
                             ID     INT )

INSERT INTO @SomeData
VALUES ( 'Book1', 'Author1', '19900330', 1 ),
       ( 'Book1', 'Author1', '19900430', 1 ),
       ( 'Book2', 'Author2', '20040330', 2 ),
       ( 'Book3', 'Author3', '20040330', 2 );
WITH cte
AS (
    SELECT *, ROW_NUMBER() over (partition by ID order by Book, Author, Dt) as RN
    FROM @SomeData
   )

SELECT a.ID
      ,a.Book
      ,a.Author
      ,a.Dt
      ,b.Book
      ,b.Author
      ,b.Dt
FROM cte AS a LEFT JOIN cte AS b ON a.id = b.id
                                AND a.RN < b.RN
WHERE a.RN = 1

答案 1 :(得分:1)

需要row_number然后查找差异

WITH cte
AS (
      SELECT table.*, ROW_NUMBER() over (partition by ID order by author) as RN
      FROM Table
   ) 

select b1.id, b2.id, b1.date, b2.date
  from cte b1 
  join cte b2 
    on b1.id = b2.id 
   and b1.rn < b2.rn 
   and b1.date <> b2.date;

WITH cte
    AS (
          SELECT table.*, ROW_NUMBER() over (partition by ID order by author) as RN
          FROM Table
       ) 

select b1.id, b2.id, b1.author, b2.author
  from cte b1 
  join cte b2 
    on b1.id = b2.id 
   and b1.rn < b2.rn 
   and b1.author<> b2.author;