[英]How to select values where column names are from another table in SQL?
I have two tables table B has some column names of table A which are divide into different groups, now I want to select data from A which belong to a certain group in B, how to write such query?我有两个表,表B有表A的一些列名,它们被分成不同的组,现在我想从A中的select数据属于B中的某个组,如何写这样的查询?
To illustrate为了显示
Table A looks like this表A看起来像这样
|key|c1|c2|c3|c4|
|p1 |11|21|23|23|
|p2 |10|22|33|21|
|p3 |20|32|53|90|
|p4 |20|42|43|98|
Table B looks like this表B看起来像这样
|cloumnName|Group|
|c1|g1|
|c2|g1|
|c3|g2|
|c4|g2|
I know to select c1 c2 from B is我知道 B 的 select c1 c2 是
select columnName from B where Group='g1'
However how can I select data from table A where key='p1' and contains the columns(c1, c2) from the result above?但是,我如何从表 A 中获取 select 数据,其中 key='p1' 并包含上述结果中的列(c1,c2)? like (p1, 11,21)
喜欢 (p1, 11,21)
you can do pivot and join你可以拨打 pivot 加入
select b.*,a.* from
(select max(case when cloumnName='c1' then [group] end) as c1,
max(case when cloumnName='c2' then [group] end) as c2,
max(case when cloumnName='c3' then [group] end) as c3,
max(case when cloumnName='c4' then [group] end) as c4
from tableB
) b join tableA a on b.c1=a.c1 and b.c2=a.c2 and b.c3=a.c3 and b.c4=a.c4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.