Sql 在Postgres/Rails中按月计算员工离职率
我有一个Rails/PostgreSQL web应用程序,其中包含以下格式的employees表:Sql 在Postgres/Rails中按月计算员工离职率,sql,ruby-on-rails,activerecord,data-science,data-analysis,Sql,Ruby On Rails,Activerecord,Data Science,Data Analysis,我有一个Rails/PostgreSQL web应用程序,其中包含以下格式的employees表: # == Schema Information # # Table name: employees # # id :bigint(8) not null, primary key # first_name :string # last_name :string # hired_datetime
# == Schema Information
#
# Table name: employees
#
# id :bigint(8) not null, primary key
# first_name :string
# last_name :string
# hired_datetime :datetime
# terminated_datetime :datetime
我想制作一个员工保留率按月图表,如下所示(但按所有12个月或过去12个月计算):
我如何生成查询(使用ActiveRecord或straight SQL)来生成此图表所需的数据?如果您试图保留年、月组合,我建议使用date\u trunc,否则使用date\u part 从那里,您可以创建聚合函数,如
count
SELECT count(*), date_trunc('month', terminated_datetime)
FROM employees
GROUP BY date_trunc('month', terminated_datetime);
或者,在后面的查询中,如果您正在查找2018年12月的特定员工记录(包括第一次、最后一次等):
SELECT *, date_trunc('month', terminated_datetime)
FROM employees
WHERE date_trunc('month', terminated_datetime) = '2018-12-01 00:00:00';
然后,您可能会再次查看12月份离职的所有员工(无论是哪一年):
SELECT *, date_trunc('month', terminated_datetime)
FROM employees
WHERE date_trunc('month', terminated_datetime) = '2018-12-01 00:00:00';
SELECT *, date_part('month', terminated_datetime)
FROM employees
WHERE date_part('month', terminated_datetime) = 12;