将行转换为列Firebird 2.5

Niz*_*ulk 5 sql firebird pivot multiple-columns firebird2.5

序列:

   
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 

必须返回select指令

|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

列是从table1id存在时的描述,table2或者是"alternate-value" 列时的描述,当table1Id为null时.

可能吗?或者我是否需要动态构造查询?

小智 6

好吧,是的,它是可能的(如果分两步完成),但它有点复杂,所以我不确定你是否应该这样做.首先,您可以执行以下选择:

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
Run Code Online (Sandbox Code Playgroud)

然后你必须运行结果.请注意,我使用的是MyValue而不是Value,并且列可能不会按照您希望的顺序出现(尽管这也可能).

数据透视表在Firebird中不容易转换为SQL,我通常更喜欢在Excel而不是Firebird中创建数据透视表,但正如您所看到的那样.