我在下面的桌子上看
ID Date IsFull
1 2020-01-05 0
1 2020-02-05 0
1 2020-02-25 1
1 2020-03-01 1
1 2020-03-20 1
我想显示ID = 1的月数
在给定的月份中有sum(isfull)/ count(*)> .6(该月60%以上的时间中isfull = 1)
所以最终输出应该
ID HowManyMonths
1 1 --------(Only month 3----2 out 2 cases)
如果问题变为sum(isfull)/ count(*)> .4
那么最终输出应该是
ID HowManyMonths
1 2 --------(Month 2 and Month 3)
谢谢!
答案 0 :(得分:2)
您可以通过两个聚合级别来做到这一点:
[[20. 0.]
[21. 0.]
[22. 0.]
[23. 22.]
[24. 0.]
[25. 22.]
[26. 16.]
[27. 11.]
[28. 12.]
[29. 16.]
[30. 24.]
[31. 8.]
[32. 0.]
[33. 18.]
[34. 16.]
[35. 33.]
[36. 20.]
[37. 12.]
[38. 20.]
[39. 10.]
[40. 0.]
[41. 25.]
[42. 26.]
[43. 6.]
[44. 4.]
[45. 3.]
[46. 36.]
[47. 40.]
[48. 0.]
[49. 12.]]
[[20. 0.]
[21. 0.]
[22. 0.]
[23. 22.]
[24. 0.]
[25. 22.]
[26. 16.]
[27. 11.]
[28. 12.]
[29. 16.]
[30. 24.]
[31. 8.]
[32. 0.]
[33. 18.]
[34. 16.]
[35. 33.]
[36. 20.]
[37. 12.]
[38. 20.]
[39. 10.]
[40. 0.]
[41. 25.]
[42. 26.]
[43. 6.]
[44. 4.]
[45. 3.]
[46. 36.]
[47. 40.]
[48. 0.]
[49. 12.]]
子查询按id,年和月进行聚合,并使用select id, count(*) howManyMonths
from (
select id
from mytable
group by id, year(date), month(date)
having avg(1.0 * isFull) > 0.6
) t
group by id
子句筛选满足成功率的组(having
很方便)。外部查询会计算每个ID通过目标费率多少个月。