简体   繁体   English

如何 select 列名来自 SQL 中另一个表的值?

[英]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.

相关问题 如何选择表的列名,其中列数据的值中包含“%”? - How to select the column names of a table where column data contains '%' in the values? PL Sql选择其他表中不存在的列值 - PL Sql select column values where it doesnt exist in another table 如何选择行值作为另一个表的列名? - How to Select Row values as another table's column names? 如何从一个表中选择与表中的列值相匹配的数据? - How do I select data from one table where column values from that table match the conatenated column values of another table? 从表中选择所有表名来自 SQL 中另一个表的表 - Select all from tables where table names are from another table in SQL 根据另一个表的列中的值从一个表中选择列名 - Select column names from one table based off of values in column of another table 如何从SQL Server中传递的参数中选择表和列名? - How to select Table and Column Names from passed parameters in SQL Server? 从SQL中的另一个表中选择一个列和值的SUM() - SELECT a column and SUM() of values from another table in SQL 从SQL中的另一个表中获取列名 - Fetching column names from another table in SQL 编辑:问题已更改 - SQL:从表中的所有行获取列名称不在另一个表中的行 - Edit: QUESTION CHANGED - SQL: Taking all rows from table where column names are NOT in another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM