我在oracle中的表中有数据,如下面的
A_CODE B_M P_id
------ ---- ------
123 A 1
123 A 2
123 B 5
678 B 3
678 C 3
678 B 4
123 BC 2
价值" BC"是B和C.数据没有标准化,所以我们需要把它计算为B和C.我需要按照下面的每个A_CODE显示计数
A_CODE B_M COUNT
------- ---- -------
123 A 2
123 B 2
123 C 1
678 B 2
678 C 1
我如何在Oracle中执行此操作?
答案 0 :(得分:3)
您应该使用CONNECT BY
和CONNECT_BY_ROOT
。
我希望这会有所帮助:
SELECT A_CODE, B_M, COUNT (*)
FROM ( SELECT A_CODE, SUBSTR (CONNECT_BY_ROOT (B_M), LEVEL, 1) B_M
FROM your_table
CONNECT BY LEVEL <= LENGTH (B_M))
WHERE B_M IS NOT NULL
GROUP BY A_CODE, B_M
ORDER BY A_CODE;
答案 1 :(得分:0)
请尝试以下:
SELECT A_CODE, B_M, COUNT(*) "COUNT" FROM
(SELECT A_CODE, B_M
FROM
(SELECT A_CODE,
SUBSTR(B_M,x.LVL,1) B_M
FROM my_table t,
(SELECT LEVEL LVL FROM dual
CONNECT BY LEVEL <=
(SELECT MAX(LENGTH(B_M)) FROM my_table)
) x
WHERE t.B_M is not null
)
WHERE B_M IS NOT NULL
UNION ALL
SELECT A_CODE, B_M FROM my_table WHERE B_M IS NULL
)
GROUP BY A_CODE,
B_M
ORDER BY A_CODE, B_M;
答案 2 :(得分:0)
除了/* Styles go here */
.success {
background-color: green;
}
.error {
background-color: red;
}
之外,您还可以创建一个包含所有可能值的表。那就是:
my_table
然后,您应该能够通过连接获得出现次数。类似的东西:
P_VAL
-----
A
B
C
答案 3 :(得分:0)
一种选择是将此表连接到一个数据集,该数据集为您提供所需的规范化结构。
with cte_normaliser as (
select 'A' B_M, 'A' 'B_M_norm from dual union all
select 'B' B_M, 'B' 'B_M_norm from dual union all
select 'C' B_M, 'C' 'B_M_norm from dual union all
select 'BC' B_M, 'B' 'B_M_norm from dual union all
select 'BC' B_M, 'C' 'B_M_norm from dual)
select my_table.A_CODE,
n.B_M_norm,
count(*)
from my_table join
cte_normaliser n on n.B_M = my_table.B_M
group by my_table.A_CODE,
n.B_M_norm;
如果您拥有大量可变代码组合,那么使用这样的固定数据集可能是不可行的,并且该数据集可能需要动态构建。