合并多行数据

时间:2019-01-22 21:32:40

标签: sql sql-server

我在sql server表中有以下数据:


enter image description here

我需要的是根据里程公告之间的Bulletin_Number和Speed组合这些行。我需要以下输出:

enter image description here

如何在SQL Server中执行此操作?

2 个答案:

答案 0 :(得分:1)

您可以使用GROUP BYCASE WHEN尝试以下解决方案:

SELECT Bulletin_Number, Speed, 
    CASE WHEN x.dir = 1 THEN MAX(MilePost_From) ELSE MIN(MilePost_From) END AS MilePost_From,
    CASE WHEN x.dir = 1 THEN MIN(MilePost_To) ELSE MAX(MilePost_To) END AS MilePost_To
FROM (
    SELECT *, CASE WHEN MilePost_From > MilePost_To THEN 1 ELSE 0 END AS dir 
    FROM table_name
)x
GROUP BY Bulletin_Number, Speed, x.dir
ORDER BY Bulletin_Number, Speed;
  

演示: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=014d74149b394a5189f3d4f81b59086b

内部查询是原始表,带有附加列显示方向。在外面,您可以按需要列(Bulletin_NumberSpeed和新列dir)分组。使用CASE WHEN,您可以根据方向(列MIN)获得组的MAXdir值。

答案 1 :(得分:0)

是什么决定结果中的from和to是最小值还是最大值?如果from总是较小,则可以使用unpivot和group,如示例所示:

--Create a temporary table
  CREATE TABLE #Speed (Bulletin_Number int,
        Speed Float,
        MilePost_From Float,
        MilePost_To Float)

--Add the records to the table
INSERT INTO #Speed (Bulletin_Number, Speed, MilePost_From, MilePost_To) VALUES
(1502, 5, 430, 429.1),
(1502, 5, 430.5, 430),
(1502, 10, 431, 430.5),
(1502, 10, 432, 431),
(1502, 10, 433, 431),
(1502, 10, 433, 432),
(1512, 10, 20, 21),
(1512, 10, 21, 22),
(1512, 10, 22, 23),
(1512, 5, 23, 24),
(1512, 5, 24, 25)

--group by bulletin and speed and find the min and max Mile Post which comes from the unpivoted subquery
SELECT Bulletin_Number, Speed, MIN(MilePost) MilePost_From, MAX(MilePost) MilePost_To
  FROM (SELECT Bulletin_Number, Speed, MilePost, ColumnName
  FROM #Speed
  unpivot
(
  MilePost
  for ColumnName in (MilePost_From, MilePost_To )
) unpiv
  ) a
  GROUP BY Bulletin_Number, Speed