a表字段关联另一个B表多字段

a表中有 车型(c)列 月份(y)列 油耗(h)列
B表中有 车型(bc)列 一月份油耗(1h)二月份油耗(2h)三月份油耗(3h)四月份油耗(4h)五月份油耗(5h)六月份油耗(6h)七月份油耗(7h)八月份油耗(8h)九月份油耗(9h)十月份油耗(10h)十一月份油耗(11h)十二月份油耗(12h)
当a.车型=b.车型 ,a表月份值为一月时 a表油耗=b表一月份油耗
当a.车型=b.车型 ,a表月份值为二月时 a表油耗=b表二月份油耗
当a.车型=b.车型 ,a表月份值为三月时 a表油耗=b表三月份油耗
当a.车型=b.车型 ,a表月份值为四月时 a表油耗=b表四月份油耗
以此类推......一直到十二月
这个sql语句该怎么写!!!

你这是个典型的横表转竖表的问题。

1、首先将b表结构转成与a表结构一致:

select * from(
    select bc, '1h' as y, 1h as h from b
    union
    select bc, '2h' as y, 2h as h from b
    union
    select bc, '3h' as y, 3h as h from b
    union
    select bc, '4h' as y, 4h as h from b
    union
    select bc, '5h' as y, 5h as h from b
    union
    select bc, '6h' as y, 6h as h from b
    union
    select bc, '7h' as y, 7h as h from b
    union
    select bc, '8h' as y, 8h as h from b
    union
    select bc, '9h' as y, 9h as h from b
    union
    select bc, '10h' as y, 10h as h from b
    union
    select bc, '11h' as y, 11h as h from b
    union
    select bc, '12h' as y, 12h as h from b
)tb
order by bc, y

上面的tb临时表就跟a表结构一致了。


2、tb表与a表做简单的关联即可:

select * from a, (
    select bc, '1h' as y, 1h as h from b
    union
    select bc, '2h' as y, 2h as h from b
    union
    select bc, '3h' as y, 3h as h from b
    union
    select bc, '4h' as y, 4h as h from b
    union
    select bc, '5h' as y, 5h as h from b
    union
    select bc, '6h' as y, 6h as h from b
    union
    select bc, '7h' as y, 7h as h from b
    union
    select bc, '8h' as y, 8h as h from b
    union
    select bc, '9h' as y, 9h as h from b
    union
    select bc, '10h' as y, 10h as h from b
    union
    select bc, '11h' as y, 11h as h from b
    union
    select bc, '12h' as y, 12h as h from b
)tb
where a.c = tb.c and a.y = tb.y

上面SQL结果就可以直观的看到你要的数据了。

追问

我能加一下你的qq吗!在这边一下字数就满了

追答

私信你了

温馨提示:答案为网友推荐,仅供参考
相似回答