sql - 结果为左连接条件的情况
问题描述
表格1
Staff category hours cost
1 Cleaning 5 20
1 Scrubbing 6 30
1 Cleaning 8 40
2 Scrubbing 4 30
表 2
`
Staff type vendor category
1 part A Cleaning
1 full b Cleaning
1 full c Scrubbing
...’
为了加入这两个表,我添加了一个新的 col“类型”:
Case when table1.hours=8
Then ”full”
Else ”part”
End as “type”
From table1
Left join table2 on type=table2.type
And Table 1.staff =table2.staff
而Table1.category=table 2.category
我想要的结果是
Staff category Cost vendor type
1 Cleaning 20 A. Part
1 Cleaning 40 B. Full
1 Scrubbing 30 C. Part
但是 type=table2.type 条件不起作用所以它变成了
Staff category Cost vendor type
1 Cleaning 20 A. Part
1 Cleaning 20 B. part
1 cleaning 40. A Full
1. Cleaning 40 B. Full
解决方案
如果我不明白,您需要一个在 table1 中创建列然后在条件 table1.category = table2.category 和 table1.type = table2.type 上与 table2 连接的实现。如果是这种情况,您可以尝试以下方法:
SELECT t1.Staff, t1.category, t1.cost, table2.vendor, t1.type
FROM (
SELECT *, CASE WHEN table1.hours = 8 THEN "full" ELSE "part" END as type
FROM table1
) t1
INNER JOIN table2
ON t1.category = table2.category
AND t1.type = table2.type
AND t1.staff = table2.staff
推荐阅读
- twilio - 在中国通过语音通话提供一次性密码 (OTP)
- javascript - 根据选择填充下拉列表
- flutter - 如何获取包含其文件的目录的大小
- bixby - 响应第一个输入的提示时忘记第二个输入
- python - 如何在 Python 中解析二进制 XML 发布请求?
- c# - 从特定列中搜索数据,其中要从中选择的数据按特定列中的重复项排序
- android - 我应该选择的最低 SDK 版本是多少?(如 2019 年 7 月),为什么?
- java - Spring data jpa findOne throwing IncorrectResultSizeDataAccessException exception
- oracle - 基于从多个表计算的值的 Oracle PL/SQL 更新
- java - 如何在使用 CommonsRequestLoggingFilter 处理请求正文之前记录它?