使用SQL查询将两个后续行合并在一起

时间:2012-05-04 15:54:59

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

我是SQL的初学者,我在SQL中遇到以下问题。

我需要一个SQL查询来计算两个在字段[idpersone]中具有相同值的连续行之间的差异,并将它们重新组合成一行。

例如,我需要将表格转换为所需的数据,如下所示:

Table data:
idLigne | idperson | statut
--------|----------|-------
   L1         1         A
   L2         1         B
   L3         1         A
   L4         1         B
   L5         2         A
   L6         2         B
   L7         3         A
   L8         3         B

Desired output: 
idLigne | idpersonne | firstLighe | secondLigne
--------|------------|------------|------------
 L2-L1         1           L1           L2
 L4-L3         1           L3           L4
 L6-L5         2           L5           L6
 L8-L7         2           L7           L8

3 个答案:

答案 0 :(得分:3)

这是一个非常好的解决方案......

如果同一idperson有三条记录,我不确定你想要做什么。或者,如果顺序记录有不同的idperson,该怎么办。

WITH
  sequenced_data
AS
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY idperson ORDER BY idLigne) AS sequence_id,
    *
  FROM
    myTable
)
SELECT
  *
FROM
  myTable as firstLigne
LEFT JOIN
  myTable as secondLigne
    ON  secondLigne.idperson    = firstLigne.idperson
    AND secondLigne.sequence_id = firstLigne.sequence_id + 1
WHERE
  (firstLigne.sequence_id % 2) = 1

答案 1 :(得分:1)

您可以尝试这样的事情:

DECLARE @MyTable TABLE(idLigne VARCHAR(2), idperson INT, statut CHAR(1));

INSERT INTO @MyTable VALUES ('L1',1,'A')
, ('L2',1,'B')
, ('L3',1,'A')
, ('L4',1,'B')
, ('L5',2,'A')
, ('L6',2,'B')
, ('L7',3,'A')
, ('L8',3,'B')

; WITH a AS (
    SELECT idLigne=t2.idLigne+'-'+t1.idLigne
    , idpersonne=t1.idperson
    , firstLigne=t1.idLigne
    , secondLigne=t2.idLigne
    , r1=ROW_NUMBER()OVER(PARTITION BY t1.idLigne ORDER BY t2.idLigne)
    , r2=ROW_NUMBER()OVER(PARTITION BY t2.idLigne ORDER BY t1.idLigne)
    FROM @MyTable t1
    INNER JOIN @MyTable t2 ON t1.idperson=t2.idperson AND t1.statut='A' AND t2.statut='B'
)
SELECT idLigne
    , idpersonne
    , firstLigne
    , secondLigne
FROM a WHERE r1=r2
GO

结果:

enter image description here

答案 2 :(得分:1)

我无法准确推断您的查询意图。但在这里:

with a as
(
   select *, 
     (row_number() over(order by idLigne, idperson) - 1) / 2 as pair_number 
   from tbl
)
select 
   max(idligne) + '-' + min(idligne) as idLigne, 
   min(idperson) as idpersonne,
   min(idLigne) as firstlighe, max(idLigne) as secondLigne       
from a
group by pair_number

输出:

IDLIGNE IDPERSONNE  FIRSTLIGHE  SECONDLIGNE
L2-L1   1           L1          L2
L4-L3   1           L3          L4
L6-L5   2           L5          L6
L8-L7   3           L7          L8

实时测试:http://www.sqlfiddle.com/#!3/26371/20