根据日期和条件合并 table
Merge the table based on date and condition
我关注table:
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);
在这个 table type 中将是 1,2,3,4.. 这里 date 和 type 都是复合键。
如果存在相同日期,我需要将行合并到单行
并仅根据以下条件合并
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 基于 运行 日期计数。
尝试GROUP BY
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
您只需要按 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
我关注table:
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);
在这个 table type 中将是 1,2,3,4.. 这里 date 和 type 都是复合键。
如果存在相同日期,我需要将行合并到单行 并仅根据以下条件合并
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 基于 运行 日期计数。
尝试GROUP BY
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
您只需要按 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