SQL中的透视:计数不按预期工作

时间:2017-07-13 13:46:09

标签: sql oracle responsys

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

  • 状态

  • LOCATION_ID

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

这似乎是出现here

的确切示例

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

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

数据透视表中显示的值只是列名:

输出:

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

当然会给我我想要的值,但是将它们显示为列而不是数据透视表

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

示例数据:

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

表数据类型:

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

1 个答案:

答案 0 :(得分:2)

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

    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))

enter image description here