我正在试图压扁一张桌子以取出电话号码,但我遇到了一些困难。当没有重复TypeID时,下面的代码工作正常,但只要它返回相同的电话号码。有没有办法可以提取下一个尚未撤出的电话号码?
查询
SELECT debtorid,
MAX( DECODE( TypeID , 1 , TELNO) ) AS Phone1 ,
MAX( DECODE( TypeID , 2 , TELNO ) ) AS Phone2 ,
MAX( DECODE( TypeID , 3 , TELNO ) ) AS Phone3 ,
MAX( DECODE( TypeID , 4 , TELNO ) ) AS Phone4,
MAX( DECODE( TypeID , 4 , TELNO ) ) AS Phone5
FROM PUB."DebtorTelNo"
where "DebtorTELNO"."DebtorId" = '123123' and "Superseded" = 0
GROUP BY DebtorId
表
DebtorID TelNo Superseded TelPTR TYPEID
123123 07920155555 0 1 1
123123 01732XXXXXX 0 6 2
123123 0161XXXXXXX 0 7 3
123123 0171XXXXXXX 0 12 4
123123 0181XXXXXXX 0 15 4
123123 0191xxxxxxx 0 17 4
答案 0 :(得分:0)
你到底想做什么?在我看来,你现在所做的事情本质上是有缺陷的,因为如果有人有6个或更多的电话号码怎么办?
如果您只想将所有电话号码放在一行中,而且每个人都不需要单独的字段,我建议使用stragg之类的字符。如果您定义此功能,您可以执行以下操作:
select debtorid, stragg(TELNO) as TelList
where "DebtorTELNO"."DebtorId" = '123123' and "Superseded" = 0
group by debtorid
这会给你类似的东西:
DebtorID TelList
123123 07920155555,01732XXXXXX,0161XXXXXXX,0171XXXXXXX,0181XXXXXXX,0191xxxxxxx
答案 1 :(得分:0)
您可以尝试以下操作:
创建一些子查询,这些子查询在类型为正确时为您提供telno,否则为NULL(非常类似于您),但也为行编号。像
这样的东西select rownum r, x.* from (
select debtorid, decode(typeid,1,telno) phone1
from xxx
order by debtorid, decode(typeid,1,telno)
)
为每个typeid创建一个这样的查询。加入他们所有,所以debtorid和r(即rownum)匹配。
现在你几乎拥有了你想要的东西,除了有些行所有列都是null。过滤掉这些。
所以你最终会得到像
这样的东西select a.debtorid, phone1, phone2, phone3, phone4 from
(select rownum r, x.* from (select debtorid, decode(typeid,1,telno) phone1 from xxx order by debtorid, decode(typeid,1,telno)) x) a,
(select rownum r, x.* from (select debtorid, decode(typeid,2,telno) phone2 from xxx order by debtorid, decode(typeid,2,telno)) x) b,
(select rownum r, x.* from (select debtorid, decode(typeid,3,telno) phone3 from xxx order by debtorid, decode(typeid,3,telno)) x) c,
(select rownum r, x.* from (select debtorid, decode(typeid,4,telno) phone4 from xxx order by debtorid, decode(typeid,4,telno)) x) d
where
a.debtorid = b.debtorid
and b.debtorid = c.debtorid
and c.debtorid = d.debtorid
and a.r = b.r
and b.r = c.r
and c.r = d.r
and phone1||phone2||phone3||phone4 is not null
;
使用您的数据返回:
Debtorid|phone1 |phone2 |phone3 |phone4 |
---------------------------------------------------------
123123|07920155555|01732XXXXXX|0161XXXXXXX|0171XXXXXXX|
123123| | | |0181XXXXXXX|
123123| | | |0191xxxxxxx|
添加另一个telno也看起来没问题
0:opal@spmdtz> insert into xxx values (123123, 'new1',2);
Debtorid|phone1 |phone2 |phone3 |phone4 |
---------------------------------------------------------
123123|07920155555|01732XXXXXX|0161XXXXXXX|0171XXXXXXX|
123123| |new1 | |0181XXXXXXX|
123123| | | |0191xxxxxxx|
添加另一个债务人ID
也是如此0:opal@spmdtz> insert into xxx values (123124, 'new2',2);
Debtorid|phone1 |phone2 |phone3 |phone4 |
---------------------------------------------------------
123123|07920155555|01732XXXXXX|0161XXXXXXX|0171XXXXXXX|
123123| |new1 | |0181XXXXXXX|
123123| | | |0191xxxxxxx|
123124| |new2 | | |
代码可能包含一些微妙的错误,但我相信编号行和连接匹配rownums的一般想法可能是正确的。