【问题标题】:How to join select two tables with condition on column sql如何在列 sql 上连接选择两个具有条件的表
【发布时间】: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


    【解决方案1】:

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

    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
    

    【讨论】:

    • 好的,谢谢老哥,抱歉回复晚了,最近我又有了一个项目,刚好有时间再次打开堆栈溢出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多