首页 > 解决方案 > 如何在列 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

我的选择案例有什么问题?

标签: sqlsql-servertsqlpivotcase

解决方案


您需要聚合以透视数据集:

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

推荐阅读