我的学校项目需要这个我无法创建的查询。
该表包含4列:
document id
,party_id
,full name
,party role
。
对于doc_id
我有2行,grantor
1为grantee
。
我想做单排,但我没有成功的情况下。
请帮忙。
SELECT document_id,
case when party_role ='grantor' then full_name
case when party_role ='grantee' then full_name
from sales.all_sales
答案 0 :(得分:2)
SELECT document_id,
CASE(party_role)
WHEN 'grantor'
THEN full_name
WHEN 'grantee'
THEN full_name
ELSE ''
END
FROM sales.all_sales
答案 1 :(得分:0)
SELECT DISTINCT document_id,
case when party_role ='grantor' then full_name end Grantor,
case when party_role ='grantee' then full_name end Grantee
from sales.all_sales
如果你想聚合字段,请尝试:
SELECT DOCUMENT_ID,
LISTAGG(GRANTOR,',') WITHIN GROUP (ORDER BY GRANTOR) GRANTOR,
LISTAGG(GRANTEE,',') WITHIN GROUP (ORDER BY GRANTEE) GRANTEE
FROM (
SELECT DISTINCT document_id,
case when party_role ='grantor' then full_name end Grantor,
case when party_role ='grantee' then full_name end Grantee
from sales.all_sales
)
GROUP BY DOCUMENT_ID
答案 2 :(得分:0)
您想要聚合。您希望每个document_id有一个结果行,因此按其分组。您希望每个都构建一系列授权者和受赠者。请使用LISTAGG
。
select
document_id,
listagg(case when party_role = 'grantor' then full_name end, ',')
within group (order by full_name) as grantor,
listagg(case when party_role = 'grantee' then full_name end, ',')
within group (order by full_name) as grantee
from sales.all_sales
group by document_id;
答案 3 :(得分:0)
在Oracle 11g中,您可以使用pivot
和listagg
作为聚合函数来执行此操作:
select * from t
pivot (listagg(name, ', ') within group (order by name)
for role in ('grantor' grantors, 'grantee' grantees))
演示:
with t(id, name, role) as (
select 2, 'James', 'grantor' from dual union all
select 2, 'Tom', 'grantor' from dual union all
select 2, 'Victoria', 'grantee' from dual union all
select 2, 'Anty', 'grantee' from dual )
select * from t
pivot (listagg(name, ', ') within group (order by name)
for role in ('grantor' grantors, 'grantee' grantees))
结果:
ID GRANTORS GRANTEES
---------- --------------- -----------------
2 James, Tom Anty, Victoria