SQL合并两行并填充另一行中缺少值的列

时间:2018-02-17 20:57:38

标签: sql sql-server

我无法合并行,需要帮助才能搞清楚。 想法是每当有多个行具有相同的groupid然后我想 合并两行并使用具有值的空列填充空列。 这特别成问题,我永远不会知道哪一列是空的,并且groupid可能在3行以上(远程但可能)相同。这是示例sql数据

    if object_id('tempdb..#deleteme') is not null drop table #deleteme;

    CREATE TABLE #deleteme(
        [groupid] [varchar](82) NULL,
        [col_1] [varchar](5) NULL,
        [col_2] [varchar](5) NULL,
        [col_3] [varchar](5) NULL,
        [col_date] [datetime] NULL
    )

    INSERT #deleteme ([groupid], [col_1], [col_2], [col_3], [col_date]) VALUES (N'0022017', N'100', N'0.0', N'0.0', CAST(N'2017-11-24 14:09:44.537' AS DateTime));
    INSERT #deleteme ([groupid], [col_1], [col_2], [col_3], [col_date]) VALUES (N'0032203', N'0', N'1.70', N'0.0', CAST(N'2017-11-24 13:44:58.797' AS DateTime));
    INSERT #deleteme ([groupid], [col_1], [col_2], [col_3], [col_date]) VALUES (N'0043108', N'1', N'0.0', N'0.950', CAST(N'2017-11-24 14:11:17.740' AS DateTime));
    INSERT #deleteme ([groupid], [col_1], [col_2], [col_3], [col_date]) VALUES (N'0043108', N'0', N'1.25', N'0.0', CAST(N'2017-11-24 14:11:09.203' AS DateTime));

    groupid col_1   col_2   col_3   col_date
    0022017 100     0.0     0.0     2017-11-24 14:09:44.537
    0032203 0       1.70    0.0     2017-11-24 13:44:58.797
    0043108 1       0.0     0.950   2017-11-24 14:11:17.740--merge this
    0043108 0       1.25    0.0     2017-11-24 14:11:09.203--and merge this

使用sql无法完成的所需输出如下所示

groupid col_1   col_2   col_3   col_date
0043108 1       1.25    0.950   2017-11-24 14:11:17.740
0043108 1       1.25    0.950   2017-11-24 14:11:09.203

我已经从结果中省略了其他2个唯一的行,我希望有人可以帮我解决这个问题。感谢

2 个答案:

答案 0 :(得分:1)

这应该这样做:

SELECT groupid, 
(SELECT max(col_1) FROM #deleteme dtm1 WHERE dtm1.groupid = dtm.groupid) AS col_1,
(SELECT max(col_2) FROM #deleteme dtm1 WHERE dtm1.groupid = dtm.groupid) AS col_2,
(SELECT max(col_3) FROM #deleteme dtm1 WHERE dtm1.groupid = dtm.groupid) AS col_3, col_date 
FROM #deleteme dtm

答案 1 :(得分:0)

不确定“合并”行的含义。如果你的意思是当col1,col2或col3中的值为0时,你从具有相同id的另一行中的那一列中选择值,那么你应该决定该值是MAX,还是以不同的方式计算办法。对于MAX解决方案,它可能如下所示:

SELECT d1.groupid, CASE WHEN d1.col_1 > 0 THEN d1.col_1 ELSE xt.col1Merged END AS Col1
, CASE WHEN d1.col_1 > 0 THEN d1.col_2 ELSE xt.col2Merged END AS Col2
, CASE WHEN d1.col_3 > 0 THEN d1.col_3 ELSE xt.col3Merged END AS Col3
FROM #deleteme d1
INNER JOIN (
    SELECT d.groupid, MAX(d.col_1) AS col1Merged, MAX(d.col_2) AS col2Merged, 
    MAX(d.col_3) AS col3Merged
    FROM #deleteme d
    GROUP by d.groupid
) xt ON xt.groupid = d1.groupid