Pivot in SQL:计数未按预期工作

Pivot in SQL: count not working as expected

我的 Oracle Responsys 数据库中有一个 table,其中包含包含其他两个变量的记录:

我想统计按状态和 location_id 分组的记录数,并将其显示为数据透视表 table。

这似乎是出现的确切示例 here

但是当我使用以下请求时:

select * from 
    (select status,location_id from $a$ ) 
        pivot (count(status) 
        for location_id in (0,1,2,3,4)
    ) order by status

枢轴 table 中出现的值只是列名 :

输出:

status    0    1    2    3    4
-1        0    1    2    3    4
1         0    1    2    3    4
2         0    1    2    3    4
3         0    1    2    3    4
4         0    1    2    3    4
5         0    1    2    3    4

我还尝试了以下内容:

select * from 
     (select status,location_id , count(*) as nbreports 
       from $a$ group by status,location_id ) 
              pivot (sum(nbreports) 
              for location in (0,1,2,3,4)
    ) order by status

但它给了我相同的结果。

 select status,location_id , count(*) as nbreports 
 from $a$ 
 group by status,location_id

当然会给我想要的值,但将它们显示为列而不是枢轴 table

如何让数据透视表 table 在每个单元格中包含行和列中具有状态和位置的记录数?

示例数据:

CUSTOMER,STATUS,LOCATION_ID
1,-1,1
2,1,1
3,2,1
4,3,0
5,4,2
6,5,3
7,3,4

table数据类型:

CUSTOMER    Text Field (to 25 chars)
STATUS  Text Field (to 25 chars)
LOCATION_ID Number Field

请检查我对您的要求的理解是否正确,您可以将位置列反之亦然

    create table test(
    status varchar2(2),
    location number
    );

    insert into test values('A',1);
    insert into test values('A',2);
    insert into test values('A',1);
    insert into test values('B',1);
    insert into test values('B',2);

    select * from test;

    select status,location,count(*)
    from test 
    group by status,location;

    select * from (
    select status,location
    from test 
    ) pivot(count(*) for (status) in ('A' as STATUS_A,'B' as STATUS_B))