【问题标题】:How to get employee ID with increment of 20% and how many times he got the increment in Sql/Python如何获取增量为 20% 的员工 ID 以及他在 Sql/Python 中获得增量的次数
【发布时间】:2022-06-10 19:55:20
【问题描述】:

我有一个包含以下值的表格:-

我想在 python/pyspark 中编写一个代码,我需要在其中找到获得 20% 或更多增量的员工代码。另外,我需要他获得增量的次数。

【问题讨论】:

    标签: python-3.x pyspark apache-spark-sql


    【解决方案1】:

    使用窗口函数。

    w=Window.partitionBy('emp_id').orderBy(to_date('salary_month_year'))
    df1 = (df.withColumn('new_salary',lag('salary').over(w)).fillna(0)#Find previous salary in each row
             .withColumn('%increase', when(col('new_salary')==0,0)
             .otherwise(round((col('salary')-col('new_salary'))/col('salary'),1)*100))#Where group starts make it 0, and rest compute increment
              .withColumn('incr_count',sum((col("%increase")>0).cast('int')).over(w))#Compute increment count
              .where(col("%increase")>20).drop('new_salary')#Filter where salary >20% and drop unwanted column
          ).show()
    
    
    +------+-----------------+------+---------+----------+
    |emp_id|salary_month_year|salary|%increase|incr_count|
    +------+-----------------+------+---------+----------+
    |     1|           Mar-22|   400|     50.0|         2|
    |     1|           Apr-22|   550|     30.0|         2|
    |     2|           Feb-22|   500|     30.0|         1|
    |     4|           Feb-22|   800|     30.0|         1|
    +------+-----------------+------+---------+----------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-29
      • 2017-02-15
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      相关资源
      最近更新 更多