sql - 如何根据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 做一些事情,但显然没有奏效。
解决方案
如果您知道每辆车的“物品”数量,则可以使用条件聚合:
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 数组中。
推荐阅读
- cocos2d-iphone - Box2D 和 Cocos2d-x 坐标
- azure-aks - 不能使用节点资源组之外的静态 IP 地址
- azure-cosmosdb - 使用 cosmonaut 库通过 id 获取 cosmosdb 文档不起作用
- oracle - Oracle IMPDP REMAP_DIRECTORY 的正确语法
- c# - c#如何引用动态创建的组合框?
- nginx - Openresty:ngx.var vs ngx.ctx
- angular - AngularFire2 v5 Angular 身份验证
- c - 更改文件指针路径时无法写入内存
- angular - 自定义数据集对象未在 Angular 6 中设置 chart.js 条形图颜色
- angular - npm 错误!npm install 时超出最大调用堆栈大小(角度)