SQL查询合并记录

时间:2018-01-25 08:33:37

标签: sql-server sql-server-2012

基本上我想在查询中创建这个结果:

enter image description here

从上表到下表(新记录)

已经尝试使用CTE,但我没有解决这个问题的线索,只是坚持如何开始。

谢谢。

1 个答案:

答案 0 :(得分:1)

试试这个

DECLARE @T TABLE
(
    Field1 DATETIME,
    Field2 VARCHAR(20),
    Field3 VARCHAR(20),
    Field4 VARCHAR(20),
    Field5 VARCHAR(20),
    Field6 INT,
    Field7 INT,
    Field8 VARCHAR(20),
    Field9 INT
)

INSERT INTO @T
VALUES('12/17/2017 10:39:00','A','AA','HB','KT',123,1234,'Over',1000),
('12/17/2017 10:42:00','B','BB','2506','8239',456,789,'Over',850),
('12/17/2017 10:47:00','A','AA','HB','KT',123,1234,'Over',850),
('12/17/2017 10:50:00','B','BB','2506','8239',456,789,'Over',700)

;WITH CTE
AS
(
    SELECT
       RN = ROW_NUMBER() OVER(PARTITION BY MAX(Field2) ORDER BY CAST(Field1 AS DATE)),
       Field1D = CAST(Field1 AS DATE),
       Field1Tmin = MIN(CAST(Field1 AS TIME)) OVER(PARTITION BY MAX(Field2)),
       Field1Tmax = MAX(CAST(Field1 AS TIME)) OVER(PARTITION BY MAX(Field2)),
       Field2 = MAX(Field2),
       Field3 = MAX(Field3),
       Field4 = MAX(Field4),
       Field5 = MAX(Field5),
       Field6 = MAX(Field6),
       Field7 = MAX(Field7),
       Field8 = MAX(Field8),
       Field9 = SUM(Field9)
       FROM @T
          GROUP BY CAST(Field1 AS DATE),CAST(Field1 AS TIME)
)
SELECT 
    DISTINCT
    Field1 = CAST(Field1Tmin AS VARCHAR(20))+'-'+CAST(Field1Tmax AS VARCHAR(20)),
    Field2,
    Field3,
    Field4,
    Field5,
    Field6,
    Field7,
    Field8,
    Field9 = SUM(Field9) OVER(PARTITION BY CAST(Field1Tmin AS VARCHAR(20))+'-'+CAST(Field1Tmax AS VARCHAR(20)))/COUNT(1) OVER(PARTITION BY CAST(Field1Tmin AS VARCHAR(20))+'-'+CAST(Field1Tmax AS VARCHAR(20)))
    FROM CTE

结果

enter image description here

我知道这不是一个直接的方式,但这可能适合你的情况。