我有一张表,每个条目都有一个计数器对
Customer
Name Value
Bob 3
Bob 4
Sam 0
Sam 1
Joe 9
我想要以下结果
Customer
Name Value1 Value2
Bob 3 4
Sam 0 1
Joe 9
我已经阅读了这个帖子Oracle query to put rows at odd number adjacent to even number,但是我想避免使用MOD函数而不是使用pivot。
答案 0 :(得分:1)
如果每个名称只有两个值,则不能在此处使用pivot语句(它也适用于日期,因为我们可以使用日期的最大值和分钟数):
select name, min(value) value1, nullif(max(value), min(value)) value2
from customer_tables
group by name
如果Bob,Sam和其他人有更多这两个值:
with t (Name, Value) as (
select 'Bob',3 from dual union all
select 'Bob',4 from dual union all
select 'Sam',0 from dual union all
select 'Sam',1 from dual union all
select 'Joe',9 from dual
), t1 (name, value, rn) as (
select name, value, ROW_NUMBER() OVER(partition by name order by value) from t
)
select * from t1
pivot XML (
max(value)
for rn in (ANY)
)
SQL> l
1 with t (Name, Value) as (
2 select 'Bob',3 from dual union all
3 select 'Bob',4 from dual union all
4 select 'Sam',0 from dual union all
5 select 'Sam',1 from dual union all
6 select 'Joe',9 from dual
7 ), t1 (name, value, rn) as (
8 select name, value, ROW_NUMBER() OVER(partition by name order by value) from t
9 )
10 select * from t1
11 pivot XML (
12 max(value)
13 for rn in (ANY)
14* )
SQL> /
NAM RN_XML
--- --------------------------------------------------------------------------------
Bob <PivotSet><item><column name = "RN">1</column><column name = "MAX(VALUE)">3</col
umn></item><item><column name = "RN">2</column><column name = "MAX(VALUE)">4</co
lumn></item></PivotSet>
Joe <PivotSet><item><column name = "RN">1</column><column name = "MAX(VALUE)">9</col
umn></item></PivotSet>
Sam <PivotSet><item><column name = "RN">1</column><column name = "MAX(VALUE)">0</col
umn></item><item><column name = "RN">2</column><column name = "MAX(VALUE)">1</co
lumn></item></PivotSet>
详细了解pivot here