如何在oracle中组合和计算两列?

时间:2016-07-17 13:27:22

标签: sql oracle

我的桌子看起来像这样;

A          B
1          100
1          102
1          105
2          100
2          105
3          100
3          102 

我想要这样的输出:

A          Count(B)
1           3 
1,2         2
1,2,3       3
2           2
3           2
2,3         2  

我该怎么做?

我尝试使用listagg,但它没有用。

2 个答案:

答案 0 :(得分:0)

我怀疑你想要计算数据中A组的数量 - 并且你的样本结果搞砸了。

如果是这样的话:

select grp, count(*)
from (select listagg(a, ',') within group (order by a) as grp
      from t
      group by b
     ) b;

这为您提供数据中存在的完整组合的计数。结果将是:

1,2,3    1
1,3      1
1,2      1

您可以通过执行以下操作获取原始行数:

select grp, sum(cnt)
from (select listagg(a, ',') within group (order by a) as grp, count(*) as cnt
      from t
      group by b
     ) b;

答案 1 :(得分:0)

Oracle安装程序

CREATE TABLE table_name ( A, B ) AS
SELECT 1, 100 FROM DUAL UNION ALL
SELECT 1, 102 FROM DUAL UNION ALL
SELECT 1, 105 FROM DUAL UNION ALL
SELECT 2, 100 FROM DUAL UNION ALL
SELECT 2, 105 FROM DUAL UNION ALL
SELECT 3, 100 FROM DUAL UNION ALL
SELECT 3, 102 FROM DUAL;

<强>查询

SELECT A,
       COUNT(B)
FROM   (
  SELECT SUBSTR( SYS_CONNECT_BY_PATH( A, ',' ), 2 ) AS A,
         B
  FROM   table_name
  CONNECT BY PRIOR B = B
  AND    PRIOR A + 1 = A
)
GROUP BY A
ORDER BY A;

<强>输出

A       COUNT(B)
----- ----------
1              3 
1,2            2 
1,2,3          1 
2              2 
2,3            1 
3              2