代码之家  ›  专栏  ›  技术社区  ›  Lajith

基于日期和条件合并表

  •  1
  • Lajith  · 技术社区  · 6 年前

    我有下表:

    DROP TABLE IF EXISTS t
    
    CREATE TABLE t
    (
        id INT IDENTITY PRIMARY KEY,
        dt datetime,
        type int,
        grp int,
        typecol1 varchar(10),
        typecol2 varchar(10),
        typecol3 varchar(10),
        typecol4 varchar(10)
    )
    
    INSERT INTO t (dt,type,grp,typecol1,typecol2,typecol3,typecol4) 
    VALUES
    ('2019-01-15',1,1,'A',null,null,null),
    ('2019-01-15',2,2,null,'B',null,null),
    ('2019-01-15',3,3,null,null,'C',null),
    ('2019-01-15',4,4,null,null,null,'D'),
    ('2019-02-15',1,1,'AA',null,null,null),
    ('2019-02-15',4,2,null,null,null,'DD'),
    ('2019-03-15',3,1,null,null,'CCC',null),
    ('2019-04-15',2,1,null,'BBBB',null,NULL);
    

    在这张桌子上 类型 将是1,2,3,4。。这里日期和类型都是复合键。

    如果单行中存在相同日期,则需要合并行。 并仅基于以下条件合并

    if same date & 
       type=1 then merge to typecol1
       type=2 then merge to typecol2
       type=3 then merge to typecol3
       type=4 then merge to typecol4
    

    grp col基于运行日期计数。

    Expected Out put :

    2 回复  |  直到 6 年前
        1
  •  2
  •   Dale K    6 年前

    尝试 GROUP BY

    FIDDLE DEMO

    SELECT dt, MAX(typecol1) typecol1, MAX(typecol2) typecol2, MAX(typecol3) typecol3,
           MAX(typecol4) typecol4
    FROM t
    GROUP BY dt
    

    输出

    dt                  typecol1    typecol2    typecol3    typecol4
    15/01/2019 00:00:00 A           B           C           D
    15/02/2019 00:00:00 AA                                  DD
    15/03/2019 00:00:00                         CCC 
    15/04/2019 00:00:00             BBBB        
    
        2
  •  1
  •   Barbaros Özhan    6 年前

    你只需要分组 ID 具有 MAX() 其余列的聚合:

    SELECT dt,MAX(typecol1) as typecol1,
              MAX(typecol2) as typecol2,
              MAX(typecol3) as typecol3,
              MAX(typecol4) as typecol4
      FROM t
     GROUP BY dt
    

    Demo