Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何基于ID将同一表上的两行合并为一行_Sql_Sql Server - Fatal编程技术网

Sql 如何基于ID将同一表上的两行合并为一行

Sql 如何基于ID将同一表上的两行合并为一行,sql,sql-server,Sql,Sql Server,我有一张这样的桌子: +------------+-------------+-------------+ carId | infoId | infoTitle | Description | +------------+-------------+-------------+ 我有一些关于同一辆车的描述: +------------+-------------+-------------+ carId | infoId | infoTitle | Description | +---

我有一张这样的桌子:

+------------+-------------+-------------+
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进行一些操作,但显然没有成功。

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

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数组中。

如果它适合您的需要,您可以使用STRING_AGG来做一个长描述“11:Wheels:nice wheel,12:Paint:some nice red painting”