【问题标题】:Merging two table using SQL to change column data in single row使用SQL合并两个表以更改单行中的列数据
【发布时间】:2020-12-14 07:02:03
【问题描述】:

希望合并两个表,将表 2 中的数据作为行添加到表 1 中的数据。 有点困惑。刚接触 sql,所以在这里寻找一些建议。

表1

campID  adID    decID   
camp1   ad1    dec1 
camp1   ad1    dec2 
camp1   ad1    dec3 
        

表2

decID   decType
dec1    1
dec2    2
dec3    3

我期待的输出

campID  adID    decIDTypeA  decIDTypeB  decIDTypeC
camp1   ad1      dec1         dec2        dec3

        
        

有人可以帮我写查询吗? 我试过了

select 
t1.campID,
t1.adID,
case(
when t1.decID = t2.decID and t2.decType = 7 then t2.decID
END as decIDTypeA
when t1.decID = t2.decID and t2.decType = 7 then t2.decID
END as decIDTypeB
when t1.decID = t2.decID and t2.decType = 7 then t2.decID
END as decIDTypeC
from table1 as t1
JOIN
on table2 as t2

但它错了。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您可以连接两个表,然后应用透视逻辑:

    SELECT
        t1.campID,
        t1.adID,
        MAX(CASE WHEN t2.decType = 1 THEN t1.decID END) AS decIDTypeA,
        MAX(CASE WHEN t2.decType = 2 THEN t1.decID END) AS decIDTypeB,
        MAX(CASE WHEN t2.decType = 3 THEN t1.decID END) AS decIDTypeC
    FROM Table1 t1
    INNER JOIN Table2 t2
        ON t1.decID = t2.decID
    GROUP BY
        t1.campID,
        t1.adID;
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-03
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 2015-11-06
      • 1970-01-01
      • 2018-10-11
      相关资源
      最近更新 更多