显示按SQL Server中的聚合条件筛选的月份

时间:2019-03-26 00:41:41

标签: sql-server date aggregation

我有一个包含customer_id及其apply_date的表。我想表明2016年的所有月份,申请贷款的客户数量比一年中的月平均客户数量高30%。

customer_id   apply_date
-------------------------
1             2016-01-01
2             2016-02-01
3             2016-02-01
4             2016-02-01
5             2016-03-01
6             2016-03-01
7             2016-03-01
8             2016-03-01
9             2016-04-01
10            2016-05-01
11            2017-02-01
12            2017-02-01
13            2017-02-01

在此表中,2016年每月有2个客户申请(平均10个客户除以5个月)。比月平均数高30%的术语是将平均数乘以2,再乘以1.3,得到2.6。

所需结果是我想显示每月拥有2.6个以上客户的月份。

通过使用2016年月份上方与条件匹配的表格,分别是第二个月和第五个月。

上表只是数据中的示例。

我尝试使用此代码

select 
    datepart(mm, apply_date) as month, count(*) as cnt
from 
    Leads
where 
    apply_date between '2016-01-01' and '2017-01-01'
group by 
    datepart(mm, apply_date)

但是我不知道如何根据给定的条件过滤数据。

1 个答案:

答案 0 :(得分:0)

尝试此代码:

DECLARE @Leads TABLE
(
    customer_id    INT,
    apply_date DATETIME
)

INSERT INTO @Leads(customer_id, apply_date)VALUES(1,'2016-01-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(2,'2016-02-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(3,'2016-02-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(4,'2016-02-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(5,'2016-03-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(6,'2016-03-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(7,'2016-03-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(8,'2016-03-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(9,'2016-04-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(10,'2016-05-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(11,'2017-02-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(12,'2017-02-01');
INSERT INTO @Leads(customer_id, apply_date)VALUES(13,'2017-02-01');

--SELECT * FROM @Leads

DECLARE @avgInYear DECIMAL(18,2)

SELECT @avgInYear = SUM(a.NoOfCus)/ CAST(COUNT(a.MonthNo) AS DECIMAL(18,2)) FROM (
SELECT DISTINCT MonthNo = MONTH(apply_date), COUNT(customer_id) NoOfCus FROM @Leads
where apply_date between '2016-Jan-01' and '2017-Dec-01'
GROUP BY MONTH(apply_date) ) AS a

SELECT @avgInYear = @avgInYear * 1.3

select datepart(mm,apply_date) as month, COUNT(customer_id) as cnt
from @Leads
where apply_date between '2016-Jan-01' and '2017-Dec-01'
group by datepart(mm,apply_date)
HAVING CAST(COUNT(customer_id) AS DECIMAL(18,2)) > @avgInYear