如何添加特定列值的小计?
Posted
技术标签:
【中文标题】如何添加特定列值的小计?【英文标题】:How can I add a subtotal of specific column values? 【发布时间】:2017-08-16 19:59:09 【问题描述】:这是数据集:
这是我的 SQL:
select f.DATE, f.PROD_STATUS,
count (*) AS TOTAL
from PROD_TABLE f
where DATE = '04-MAY-17'
GROUP BY f.DATE, f.PROD_STATUS
我正在尝试将 'SUCCESS'
的值作为 SQL 结果中的一列获取:
(SUCCESS = READY_1 + READY_2 + READY_3 + READY_4 + READY_5)
我希望 SQL 结果如下所示:
.
我怎样才能做到这一点?
【问题讨论】:
我认为你可以在 oracle 中使用pivot
来完成这项工作。
【参考方案1】:
检查一下:
with t as (
select 1 as ready_1,
2 as ready_2,
3 as ready_3,
1 as in_process,
4 as fail,
5 as crash,
'5/4/2017' as dat
from dual
union all
select 2 as ready_1,
2 as ready_2,
3 as ready_3,
1 as in_process,
4 as fail,
0 as crash,
'5/5/2017' as dat
from dual
)
select dat, prod_stat, max(suc) over(partition by dat) as success, sum(value) over(partition by dat) as total
from (
select dat, prod_stat, value, sum(value) over (partition by dat) as suc
from t
unpivot(
value for prod_stat in (ready_1, ready_2, ready_3)
)
union all
select dat, prod_stat, value, null as suc
from t
unpivot(
value for prod_stat in (in_process, fail, crash)
)
)
结果:
DAT PROD_STAT SUCCESS TOTAL
5/4/2017 READY_2 6 16
5/4/2017 READY_1 6 16
5/4/2017 CRASH 6 16
5/4/2017 FAIL 6 16
5/4/2017 IN_PROCESS 6 16
5/4/2017 READY_3 6 16
5/5/2017 FAIL 7 12
5/5/2017 IN_PROCESS 7 12
5/5/2017 CRASH 7 12
5/5/2017 READY_2 7 12
5/5/2017 READY_1 7 12
5/5/2017 READY_3 7 12
【讨论】:
您好 l3rutt,感谢您的回复。问题,这个子句不是使值成为静态值吗? 1 作为 ready_2, 1 作为 ready_3, 1 作为 in_process, 总共 8, 5 作为 suc, 数据集是现有数据。有8种生产状态,其中5种加起来等于成功(READY_1、2、3、4、5之和) 谢谢l3rutt。欣赏它以上是关于如何添加特定列值的小计?的主要内容,如果未能解决你的问题,请参考以下文章