我看到了一些我的问题,但我的问题并不相同(至少我能看到的问题(我有以下表:
id1 id2 column1 column2 column3 column4 column5 column6
147741 -905306891655 NULL NULL NULL NULL NULL NULL
147741 -905306891655 NULL NULL NULL NULL 2017-01-06 15:14:10.057 NULL
147741 -905306891655 NULL 2017-01-06 16:39:49.057 2017-01-06 16:39:49.057 NULL NULL NULL
147741 -905306891655 2017-01-04 15:09:20.057 NULL NULL 2017-01-06 15:26:14.057 NULL 2017-01-04 17:09:20.057
它只是我表的一部分,在真实表中,有许多ID1,ID2对,如上所述。如您所见,在每一列中,只有一个不是零值。因此,我需要做的是,压缩这些列,如下:
id1 id2 column1 column2 column3 column4 column5 column6
147741 -905306891655 2017-01-04 15:09:20.057 2017-01-06 16:39:49.057 2017-01-06 16:39:49.057 2017-01-06 15:26:14.057 2017-01-06 15:14:10.057 2017-01-04 17:09:20.057
我该怎么做?
CREATE TABLE #Table
([id1] bigint, [id2] bigint, [column1] datetime, [column2] datetime, [column3] datetime, [column4] datetime, [column5] datetime, [column6] datetime)
;
INSERT INTO #Table
([id1], [id2], [column1], [column2], [column3], [column4], [column5], [column6])
VALUES
(147741, -905306891655, NULL, NULL, NULL, NULL, NULL, NULL),
(147741, -905306891655, NULL, NULL, NULL, NULL, '2017-01-06 15:14:10.057', NULL),
(147741, -905306891655, NULL, '2017-01-06 16:39:49.057', '2017-01-06 16:39:49.057', NULL, NULL, NULL),
(147741, -905306891655, '2017-01-04 15:09:20.057', NULL, NULL, '2017-01-06 15:26:14.057', NULL, '2017-01-04 17:09:20.057')
;
SELECT id2
,id1
,max(column1)
,max(column2)
,max(column3)
,max(column4)
,max(column5)
,max(column6)
FROM #Table
GROUP BY id2
,id1
您可以使用聚合,假设每行id1
/id2
组合:
select id1, id2, max(column1) as column1, max(column2) as column2
from t
group by id1, id2;
聚合功能忽略NULL
值。