我正在处理一些代码,示例表如下所示。寻找聚合输出到某些查询
样本表
col1 col2
---- ----
val1 Fully
val1 Partial
val2 NoService
val2 Partial
val3 Fully
val3 NoService
val3 Fully
val3 Partial
val1 Fully
val2 NoService
预期输出
Col1 Fully Partial NoService Total
---- ----- ------- --------- -----
val1 2 1 0 3
val2 0 1 2 3
val3 2 1 1 4
不确定如何在oracle中执行此操作?请一些帮助
答案 0 :(得分:2)
试试这个:虽然它会提供你期望的结果,但它不是一个动态的解决方案。如果你在val2中有固定值,那么它是最好的,否则你必须选择动态方式。
SELECT col1,
SUM(CASE WHEN col2 = 'Fully' THEN 1 ELSE 0 END) Fully,
SUM(CASE WHEN col2 = 'Partial' THEN 1 ELSE 0 END) Partial,
SUM(CASE WHEN col2 = 'NoService' THEN 1 ELSE 0 END) NoService,
COUNT(col2) total
FROM yourTable
GROUP BY col1
答案 1 :(得分:1)
在Oracle中,您可以使用带有CASE
SELECT COL1,
COUNT(CASE when COL2 = 'FULLY' THEN 1 ELSE 0 END) AS FULLY,
COUNT(CASE when COL2 = 'PARTIAL' THEN 1 ELSE 0 END) AS PARTIAL
FROM TABLE_A A
LEFT JOIN TABLE_A B
on B.COL1 = A.COL1
GROUP BY COL1
答案 2 :(得分:1)
使用oracle
中的数据透视查询功能尝试此操作select * from(select nvl(col1,'Total') col1,nvl(col2,'Total') col2,count(1) cnt from mytable group by CUBE(col1,col2))
pivot
(
sum(cnt)
for col2 IN
(
'Fully' AS "Fully",
'Partial' AS "Partial",
'NoService' AS "NoService",
'Total' As "Total"
)
)
从上面的查询中我可以得到列和行的总和。
根据您的需要使用查询。