【发布时间】:2020-05-21 16:59:34
【问题描述】:
我在 sql server 中有一个表结构如下表 1
----------------------------
| 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
我的选择案例有什么问题?
【问题讨论】:
标签: sql sql-server tsql pivot case