我正在使用Oracle SQL,我需要一些查询帮助。我不知道该怎么做。
我有下表(table_a):
Mortgage_ID (int)
Doc_ID (int)
Status (varchar)每个文件可以发送多次相同的抵押贷款。
在上表中,我做了下表(table_b):
Rank (int)
Document_type (int)
Count (int)此表包含来自table_a的前40个流行文档的全局计数(不管状态如何)。例如:
Rank | Doc_ID | count
--------------------------
1 | 212121 | 90
2 | 555111 | 82
3 | 4567654 | 76
. | . | .
. | . | .
. | . | .
40 | 54321 | 22现在我需要创建下面的表格:对于来自table_a的每一笔抵押贷款,我需要为每一份状态为"OK“的前40名文档发送的文档数量。
例如:
Mortgage_id | Pop1 | Pop2 | Pop3 | ... | Pop40
-------------------------------------------------
123 | 50 | 21 | 30 | ... | 6
555 | 70 | 0 | 21 | ... | 40
654 | 100 | 96 | 58 | ... | 0Pop1文档(最流行的文档)已经被发送了50次,状态为"OK“用于Mortgage_ID 123。Pop2已经被发送了21次,状态为"OK“,用于Mortgage_id 123等等。
我希望描述得足够清楚。有人知道怎么做吗?
发布于 2014-09-29 11:18:44
基本上,这是一个组合两个表的join,然后是一个pivot。在这种情况下,我将使用条件聚合。所以,我想这就是你们要找的:
select a.mortgage_id,
sum(case when b.rank = 1 then 1 else 0 end) as pop1,
sum(case when b.rank = 2 then 1 else 0 end) as pop2,
. . .
sum(case when b.rank = 40 then 1 else 0 end) as pop40
from table_b b join
table_a a
on b.doc_id = a.doc_id
group by a.mortgage_id;发布于 2014-09-29 11:49:55
试试这个:
select *
from (select ta.Mortgage_ID, rank, cnt
from table_a ta, table_b tb
where ta.doc_id = tb.doc_id
)
pivot (
sum(cnt)
for rank in (1 pop1,2 pop2,3 pop3,4 pop4,5 pop5)
)
MORTGAGE_ID POP1 POP2 POP3 POP4 POP5
----------- ---------- ---------- ---------- ---------- ----------
1 20
2 40
5 10
4 5
3 30SQLFiddle
https://stackoverflow.com/questions/26098530
复制相似问题