[英]SQL Query to retrieve users based on date and month
I have the following table: 我有下表:
User 用户
I'm trying to get a query to get the billable users, criteria being: 我正在尝试查询要计费的用户,条件是:
I have the following query: 我有以下查询:
SELECT * from user u WHERE CompanyID = 1205
AND (p.IsActive = 1 AND MONTH(p.Date_Joined) != MONTH(GETDATE())
OR (p.is_active = 0 AND MONTH(p.Date_Left) = MONTH(GETDATE())
The problem is that this query isn't working as it doesn't check the year of the user (users joined in september 2017 are not seen as billable, even though they should as they were joined in 2017 and not this year, the persons who are created in september 2018 should not be seen as billable). 问题在于此查询无法正常运行,因为它不检查用户的年份(2017年9月加入的用户不算是可计费的,即使他们应该在2017年而不是今年加入)在2018年9月创建的用户不应被视为可计费的)。
How can I implement the year or optimize my query? 如何实施年份或优化查询?
EOMONTH
can be used to determine the last day of month. EOMONTH
可用于确定每月的最后一天。 For example: 例如:
/* last day of prev month */ EOMONTH('2018-09-05', -1) = 2018-08-31
/* last day of curr month */ EOMONTH('2018-09-05') = 2018-09-30
You can easily check if active user joined on previous month(s) or inactive user left on current month as follows: 您可以轻松地检查活动用户是上个月加入的还是当前月剩余的非活动用户,如下所示:
DECLARE @billdate AS DATE = '2018-09-05';
SELECT *
FROM user
WHERE CompanyID = 1205 AND (
(
IsActive = 1 AND
Date_Joined <= EOMONTH(@billdate, -1)
)
OR
(
IsActive = 0 AND
Date_Left > EOMONTH(@billdate, -1) AND
Date_Left <= EOMONTH(@billdate)
)
)
AND
doesn't do anything. AND
周围不会执行任何操作。 You probably wanted to put them around the OR
. OR
周围。 p
. p
没有目标表。 From the column names I think the columns prefixed with it are also from user
, so change the alias to u
. user
,因此将别名更改为u
。 year()
similar to how you used month()
. year()
类似于使用month()
。 SELECT *
FROM user u
WHERE u.companyid = 1205
AND (u.isactive = 1
AND month(p.date_joined) != month(getdate())
AND year(p.date_joined) = year(getdate())
OR u.is_active = 0
AND month(p.date_left) = month(getdate())
AND year(p.date_left) = year(getdate()));
I think you need check between current month start date and End date. 我认为您需要在当前月份的开始日期和结束日期之间进行检查。 Try this
尝试这个
DECLARE @D_FROM_DATE DATE,@D_TO_DATE DATE
SELECT @D_FROM_DATE=DATEADD(DAY,-DATEPART(DAY,GETDATE()-1),GETDATE()),
@D_TO_DATE=DATEADD(MONTH,1,DATEADD(DAY,-DATEPART(DAY,GETDATE()),GETDATE()))
SELECT * FROM USER P
WHERE P.COMPANYID = 1205
AND
(
CAST(P.DATE_JOINED AS DATE) BETWEEN @D_FROM_DATE AND @D_TO_DATE
OR
CAST(P.DATE_LEFT AS DATE) BETWEEN @D_FROM_DATE AND @D_TO_DATE
)
You can use like this 你可以这样使用
SELECT * from user u WHERE CompanyID = 1205
AND (p.IsActive = 1 AND CONCAT(YEAR(p.Date_Joined),'/',MONTH(p.Date_Joined)) != CONCAT(YEAR(GETDATE()),'/',MONTH(GETDATE())))
OR (p.is_active = 0 AND CONCAT(YEAR(p.Date_Left),'/',MONTH(p.Date_Left)) = CONCAT(YEAR(GETDATE()),'/',MONTH(GETDATE())))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.