sql - 如何在列 sql 上连接选择两个具有条件的表
问题描述
我在 sql server 中有一个表,结构如下 table1
----------------------------
| ID | year | code | value |
----------------------------
| 1 | 2019 | 41 | 33 |
| 1 | 2019 | 42 | 34 |
| 2 | 2019 | 42 | 35 |
| 2 | 2019 | 43 | 36 |
----------------------------
还有这张表2
---------------------
| ID | year | index |
---------------------
| 1 | 2019 | 15 |
| 2 | 2019 | 16 |
---------------------
不知何故我想选择加入他们,变成这样
---------------------------------------------------------------------
| ID | year | index | value_code_41 | value_code_42 | value_code_43 |
---------------------------------------------------------------------
| 1 | 2019 | 15 | 33 | 34 | 0 |
| 2 | 2019 | 16 | 0 | 35 | 36 |
---------------------------------------------------------------------
我已经尝试过这样的案例,但它在 value_code_42 和 value_code_43 中返回 0
select b.*,
case when a.value !=0 and kode=41 then a.value else 0 end as value_code_41,
case when a.value !=0 and kode=42 then a.value else 0 end as value_code_42,
case when a.value !=0 and kode=43 then a.value else 0 end as value_code_43
from table1 a, table2 b
where a.year=b.year and a.id=b.id
我的选择案例有什么问题?
解决方案
您需要聚合以透视数据集:
select
b.id,
b.year,
b.index,
max(case when a.kode = 41 then a.value else 0 end) as value_code_41,
max(case when a.kode = 42 then a.value else 0 end) as value_code_42,
max(case when a.kode = 43 then a.value else 0 end) as value_code_43
from table1 a
inner join table2 b on a.year = b.year and a.id = b.id
group by b.id, b.year, b.index
推荐阅读
- amazon-sumerian - 我们可以在 WebAR 8thWall 应用程序中删除加载栏或 8thWall 吗?
- html - 如何将 hmtl5 转换为 apk?
- typescript - 工厂模式,“IBaseDao”类型中缺少属性“findByEmail”,但在“IUserDao”类型中是必需的
- scala - Spark 内存不足异常
- html - @font-face 正在上传无法应用于我的项目的字体
- jspdf-autotable - 创建具有固定列宽确定表格宽度的 jsPDF-Autotable
- html - 如何在两个部分之间定位图像?
- javascript - 如何在AngularJs中的方法调用后绑定模型?
- jquery - 使用 Laravel 中控制器的 JSON 响应自定义错误
- c++ - 制作一个小于十的不同随机整数的列表