假设我有这个表(Postgres 9.5),它包含一个interation id,一个满意度值(1表示满足0表示不满足),以及截断到该月第一天的交互日期发生。假设无法更改此表的布局。
interaction | satisfaction | surveyed_on
------------+---------------+-------------
325524 | 1 | 2016-01-01
325999 | 1 | 2016-01-01
332642 | 0 | 2016-03-01
333152 | 1 | 2016-02-01
326765 | 0 | 2016-01-01
我如何计算每月的满意度百分比,同时考虑到几个月内可能无法获得正面或负面交互的事实。理想情况下,结果看起来像这样:
month | positive_scr | negative_scr | satisfaction_pct
------------+---------------+--------------+-----------------
2016-01-01 | 100 | 1 | 99
2016-02-01 | 10 | 5 | 50
2016-03-01 | 50 | 10 | 80
2016-04-01 | 35 | 35 | 100
谢谢!
答案 0 :(得分:1)
我将通过几个步骤来解决这个问题:
我参加了附件SQLfiddle:
select dt,
sum( case when satisfaction = 1 then 1 else 0 end ) as positive_scr,
sum( case when satisfaction = 0 then 1 else 0 end ) as negative_scr,
sum( case when satisfaction = 1 then 1 else 0 end ) * 100 / count(*) as satisfaction_pct
from (
/* If not using Postgres you will need to use your database specific function here */
select generate_series( '2016-01-01', '2016-04-01', interval '1 month' ) as dt
) as a
left join
(
select satisfaction, surveyed_on
from scores
) as b
on a.dt = b.surveyed_on
group by dt
答案 1 :(得分:0)
您可以使用这种查询来完成此操作,该查询几乎适用于所有流行的RDBMS。
注意:在处理divide by 0
时你必须处理percentage
条件,但这是特定于数据库的,所以我留下它让你弄明白。
我用来计算satisfaction percentage
的公式是100 - negative_score*(100/positive_score)
。如果您想更改它,只需将negative_score
和positive score
放在自定义公式上即可。
的 Rextester Demo
强>
select
surveyed_on,
sum(case when satisfaction=1 then 1 else 0 end) as positive ,
sum(case when satisfaction=0 then 1 else 0 end) as negative ,
(100 - (sum(case when satisfaction=0 then 1 else 0 end))
*(100/(sum(case when satisfaction=1 then 1 else 0 end)))
) as satisfaction_percent
from tbl234
group by surveyed_on;