sql - 如何在主要描述列中包含父描述?
问题描述
我有一个 sql 查询:
SELECT
Object.Description,
categories.Description AS ParentDescription
FROM ObjectInspectionLog oil
INNER JOIN Object ON oil.ObjectId = Object.ObjectId
INNER JOIN Object as categories ON Object.ParentId = categories.ObjectId
WHERE oil.Notes IS NULL
GROUP BY Object.Description, categories.Description
ORDER BY MIN(Object.ObjectId)
仅供参考:我的实际命名不使用名称对象
ObjectInspectionLog
:
ObjectInspectionLogId JobId ObjectId Notes
3, 6669, 15, NULL
4, 6669, 2, NULL
5, 6669, 3, Rear tires worn
6, 6669, 4, NULL
7, 6669, 5, NULL
8, 6669, 14, NULL
Object
ObjectId ParentId Description
1, NULL, Chassis
2, 1, Front Tires
3, 1, Rear Tires
4, 1, Windshield Condition
5, 1, Headlights
13, NULL, Adaptive Equipment
14, 13, Occupied Wheelchair Lift
15, 14, Dual post lift
目前,我返回的内容如下所示:(为简洁起见,删除了一些信息)
Description ParentDescription
Windshield Condition, Chassis
Headlights, Chassis
Occupied Wheelchair Lift, Adaptive Equipment
ETC
我的目标是获取包含父描述(机箱、自适应设备等)的列表
我想要返回的是:
Description ParentDescription
Chassis, NULL
Windshield Condition, Chassis
Headlights, Chassis
Adaptive Equipment, NULL
Occupied Wheelchair Lift, Adaptive Equipment
ETC
解决方案
看起来您想要输出对象的行,无论它们是否被 引用ObjectInspectionLog
,例如ObjectId
1
应该产生一个输出行。目前尚不清楚您为什么使用group by
.
以下代码使用outer
连接来更接近您可能想要的:
-- Sample data.
declare @ObjectInsopectionLog as Table ( ObjectInspectionLogId Int, JobId Int, ObjectId Int, Notes VarChar(32) );
insert into @ObjectInsopectionLog ( ObjectInspectionLogId, JobId, ObjectId, Notes ) values
( 3, 6669, 15, NULL ),
( 4, 6669, 2, NULL ),
( 5, 6669, 3, 'Rear tires worn' ),
( 6, 6669, 4, NULL ),
( 7, 6669, 5, NULL ),
( 8, 6669, 14, NULL );
select * from @ObjectInsopectionLog;
declare @Objects as Table ( ObjectId Int, ParentId Int, Description VarChar(32) );
insert into @Objects ( ObjectId, ParentId, Description ) values
( 1, NULL, 'Chassis' ),
( 2, 1, 'Front Tires' ),
( 3, 1, 'Rear Tires' ),
( 4, 1, 'Windshield Condition' ),
( 5, 1, 'Headlights' ),
( 13, NULL, 'Adaptive Equipment' ),
( 14, 13, 'Occupied Wheelchair Lift' ),
( 15, 14, 'Dual post lift' );
select * from @Objects;
-- Do the work.
select Child.Description, Parent.Description as ParentDescription, OIL.ObjectId as OIL_ObjectId
from @ObjectInsopectionLog as OIL full outer join -- Return all rows from either side of this join .
@Objects as Child on Child.ObjectId = OIL.ObjectId left outer join -- Return all Child rows regardless of Parent .
@Objects as Parent on Parent.ObjectId = Child.ParentId
where OIL.Notes is NULL
order by Child.ObjectId;
推荐阅读
- javascript - 如何访问控制器中的 $scope 变量?
- python - 我正在尝试在 python 中编写一个不和谐的机器人,但它说所有代码都是错误的?
- javascript - React:如何在没有索引或唯一标识符的情况下修改基于数组的状态?
- python - 使用 Python 代码显示来自 Xbee 网关接收器的字节数组数据
- javascript - 无法读取未定义的属性“加密”
- python - pandas concat/merge/join 多个数据帧,该列只有一列
- python - 将不同扩展名的文件名写入不同的文本文件
- prolog - . or 运算符在 GNU Prolog 中的表达式后预期
- react-native - React Native Animated Rotating Circles with scale dependency
- mysql - 如何求和mysql中的最大值?