在 SQL 服务器中显示按聚合条件过滤的月份

Show month filtered by aggregation condition in SQL Server

我有一个 table,其中包含 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

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

想要的结果是我想显示每个月有超过 2.6 个客户的月份。

通过在 2016 年符合条件的月份上方使用 table,即第 2 个月和第 5 个月。

上面的table只是数据中的样本。

我尝试使用此代码

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)

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

试试这个代码:

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