简体   繁体   English

根据两个表值合并 SQL 表中的行

[英]Merge Rows in SQL Table based on two table values

I have a table with travel details.我有一张包含旅行详细信息的表格。 Details are getting saved in distributed manner.详细信息以分布式方式保存。 I need to merge the rows based on Source and Destination.我需要合并基于源和目标的行。 My Source is A and Final Destination is D, I need to merge all the 3 rows into 1 with sum of time and distance, based on date of travel.我的来源是 A,最终目的地是 D,我需要根据旅行日期将所有 3 行合并为 1 行,时间和距离之和。

Table Details and Expected Output表格详细信息和预期输出

I tried using Concatenate but not able to do based on conditions.我尝试使用连接但无法根据条件进行操作。 Not sure how to combine rows of one table based on values of another.不确定如何根据另一个表的值组合一个表的行。

You can use LEFT JOIN statement and then aggregate:您可以使用LEFT JOIN语句然后聚合:

SELECT Table2.Date,
       Table2.CarID,
       Table2.Source,
       Table2.Destination,
       SUM(Table1.Distance) AS Distance,
       SUM(Table1.[Time(Hours)]) AS [Time(Hours)]
FROM Table2
LEFT JOIN Table1
     ON  (Table1.Source BETWEEN Table2.Source AND Table2.Destination
     OR  Table1.Destination BETWEEN Table2.Source AND Table2.Destination)
     AND Table2.Date = Table1.Date
     AND Table2.CarID = Table1.CarID
GROUP BY Table2.Date,
         Table2.CarID,
         Table2.Source,
         Table2.Destination

This assumes that your Source and Destination never overlap - like in the example you provided.这假设您的SourceDestination永远不会重叠 - 就像您提供的示例一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM