sql server找到同一个表的行之间的差异

时间:2015-02-12 16:51:52

标签: sql sql-server

我有一个Table员工,对于给定的empid,我想列出时间,用户名和之前发生的变化。也适用于列' req_type'我想写(正常)为0,(重要)为1,(紧急)为值2。

empid   Time                   req_type     token    requester   username    comment
------------------------------------------------------------------------------------------
10      05-01-2014 10:04:00     0             10      grusel       ann
10      05-01-2014 11:11:00     1              8                   ben       check site www:\\abc.com
10      05-01-2014 10:10:00     0              2                   ann 
12      06-01-2014 13:00:01     0              2       Jeena       bill      check www:\\someerror.com
12      07-02-2014 14:00:00     1              6        Mike       bill

Select语句应该为empid = 10提供3行,如下所示

Time                    Username          Changed
---------------------------------------------------------------------------
05-01-2014 11:11:00     ben          'req_type' updated from (normal) to (important), 
                                     'token' updated from 2 to 8,
                                     'requester' deleted,
                                     'comment' added check site www:\\abc.com
05-01-2014 10:10:00     ann          'token' updated from 10 to 2,
                                     'requester' added grusel
05-01-2014 10:04:00     ann           First entry

类似地,Select语句应该为empid = 12提供2行,如下所示

Time                    Username          Changed
----------------------------------------------------------------------------
7-02-2014 14:00:00     bill           'req_type' updated from (normal) to (important),
                                      'token' changed from 2 to 6,
                                      'requester' changed from Jeena to Mike,
                                      'comment' deleted
6-01-2014 13:00:01      bill           First entry

1 个答案:

答案 0 :(得分:0)

这是我们必须通过emp id

将最终输出转换为空格分隔文本的部分答案
CREATE TABLE emp (id int , [time] datetime, req_type int, token int )

INSERT INTO emp VALUES (1, GETDATE(), 0,1)
INSERT INTO emp VALUES (1, GETDATE()-1, 1,1)
INSERT INTO emp VALUES (1, GETDATE()-2, 1,3)

;WITH cte AS
(

SELECT *, ROW_NUMBER() OVER( PARTITION BY id ORDER BY time asc) rn  FROM emp 

),cte2 AS ( 
SELECT c2.*, CASE WHEN c.req_type != c2.req_type THEN 'Req changed from'+CONVERT(VARCHAR,c2.req_type)+' to '+CONVERT(VARCHAR,c.req_type)     ELSE '' END AS reqc, 
CASE WHEN c.token != c2.token THEN 'Token changed from' +CONVERT(VARCHAR,c2.token)+' to '+CONVERT(VARCHAR,c.token) ELSE '' END AS tokenc
 FROM cte c INNER join cte c2 ON c2.rn+1 = c.rn
 )

 SELECT id,time,req_type,reqc+tokenc AS changes FROM cte2