序列:
table1
=====
id - Description
----------------
|1 |Proj-x
|2 |Settlers
|3 |Bank
|4 |Newiest
table2
=====
id table1Id value alternate-value
---------------------------------
|1| 1 |12 |null
|1| 4 |6 | null
|1| null |22 |Desktop
|2| 2 |7 |null
|2| 3 |11 |null
|2| null |2 |Camby Jere
|3| 1 |8 |null
|3| 4 |6 |null
|3| null |7 |Camby Jere
选择指令必须返回
|table1.id|Proj-x|Settlers|Bank |Newiest|Desktop|Camby Jere
----------------------------------------------------------
|1 |12 |null |null |null |null |null
|1 |null |null |6 |null |null |null
|1 |null |null |null |null |22 |null
|2 |null |7 |null |null |null |null
|2 |null |null |11 |null |null |null
|2 |null |null |null |null |null |2
|3 |8 |null |null |null |null |null
|3 |null |null |null |6 |null |null
|3 |null |null |null |null |null |7
这些列的描述来自table1
当 id 存在于table2
或“替代值”列table1Id
一片空白。
是否可以?或者我需要动态构建查询吗?
嗯,是的,是的possible(如果分两步完成),但它有点复杂,所以我不确定你是否应该这样做。首先,您可以执行以下选择:
with tmp1(MyFieldName) as
(select distinct coalesce(t2.alternate_value, t1.Description)
from table2 t2
left join table1 t1 on t2.Table1ID = t1.id),
tmp2(MyPivotSource) as
(select 'iif(coalesce(t2.alternate_value, t1.Description) = '''||MyFieldName||''', t2.MyValue, 0) as "'||MyFieldName||'"'
from tmp1)
select 'select t2.id as "table1.id", '||list(MyPivotSource)||'from table2 t2
left join table1 t1 on t2.Table1ID = t1.id'
from rdb$database
cross join tmp2
然后你必须运行结果。请注意,我使用的是 MyValue 而不是 Value,并且列可能不会按您想要的顺序显示(尽管这也是可能的)。
数据透视表在 Firebird 中不容易转换为 SQL,我通常更喜欢在 Excel 中而不是 Firebird 中创建数据透视表,但正如您所看到的,这是可能的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)