对不起,我找不到确切的词来使标题更清楚。
我在SQL Server中有两个表,在表1中说我有两列Key1Display和Key2Display,它们的数据类型为bit
,用于控制是否在table2中显示值,并且表2将具有2列Key1和Key2。
我想要实现的是一种交叉联接,比如说表1有3行:
| Key1Display | Key2Display |
+---------------------+------------------+
| 0 | 1 |
| 1 | 0 |
| 1 | 1 |
在表2中说有2行
| Key1 | Key2 |
+---------------------+------------------+
| Row1Key1value | Row1Key2value |
| Row2Key1value | Row2Key2value |
然后基于这两个表,我想要一个查询来显示6(2 * 3)行和1列结果,如下所示:
null:Row1Key2value
Row1Key1Value:null
Row1Key1Value:Row1Key2value
null:Row2Key2value
Row1Key2Value:null
Row1Key2Value:Row2Key2value
答案 0 :(得分:3)
类似这样:
select
case when t1.Key1Display = 1 then coalesce(t2.Key1,'??') else 'null' end
+ ':' + case when t1.Key2Display = 1 then coalesce(t2.Key2,'??') else 'null' end
-- And so on for as many keys as you have
from table1 t1
cross join table2 t2