首页 > 解决方案 > 如何根据ID将同一表上的两行合并为一行

问题描述

我有一个看起来像这样的表:

+------------+-------------+-------------+
carId | infoId | infoTitle | Description |  
+------------+-------------+-------------+

我有一些关于同一辆车的描述:

+------------+-------------+-------------+
carId | infoId | infoTitle | Description |  
+------------+-------------+-------------+

1     | 11     | Wheels    | nice wheels |
1     | 12     | Paint     | some nice red painting |

我需要将这两个信息加入同一辆车。输出将如下所示:

+------------+-------------+-------------+---------+------------+--------------+
carId | infoId | infoTitle | Description | infoId2 | infoTitle2 | Description2 |  
+------------+-------------+-------------+---------+------------+--------------+

1     | 11     | Wheels    | nice wheels | 12      | Paint      | some nice red painting |

问题是我没有与同一辆车相关的信息的固定编号,因此我需要一个查询,为与该车相关的每个信息添加一个新列

我试图用 SELECT DISTINCT 做一些事情,但显然没有奏效。

标签: sqlsql-server

解决方案


如果您知道每辆车的“物品”数量,则可以使用条件聚合:

select carid,
       max(case when seqnum = 1 then infoid end) as infoid_1,
       max(case when seqnum = 1 then infotitle end) as infotitle_1,
       max(case when seqnum = 1 then description end) as description_1,
       max(case when seqnum = 2 then infoid end) as infoid_2,
       max(case when seqnum = 2 then infotitle end) as infotitle_2,
       max(case when seqnum = 2 then description end) as description_2
from (select t.*,
             row_number() over (partition by carid order by infoid) as seqnum
      from t
     ) t
group by carid;

您可以轻松地将其扩展到更多项目。您可以使用以下方法获得最大数量:

select top (1) count(*)
from t
group by carid
order by count(*) desc;

如果您不知道最大值,那么这会更加棘手,因为 SQL 查询会返回一组固定的列。您可以使用动态 SQL 来构造您想要的 SQL。或者您可以决定更改您的数据表示。例如,您可以将值聚合到 JSON 数组中。


推荐阅读