我一直无法找到帮助我返回以下内容的WHERE
或HAVING
条件:
如果用户在过去一个月内记录了活动,我想为这些用户返回过去六(6)个月的记录。到目前为止我一直在使用以下查询...
SELECT
USER,
CAST(ACTIVITY AS DATE),
COUNT(DISTINCT ACTIONS),
SUM(RESULTS)
FROM
TABLE
WHERE
ACTIVITY >= DATEADD(MONTH, -6, GETDATE())
GROUP BY
[conditions]
ORDER BY
[conditions]
我试图使用
HAVING
(COUNT(USER) * CAST(DATEADD(MONTH, -1, GETDATE()) AS DECIMAL)) > 0
但我收到的是非活动用户的记录返回,这些用户只在过去六(6)个月内记录了操作,而不是当前或最近一个月。
救命?!!
提前致谢,
您可以将exists
运算符与子查询一起用于上个月具有活动的用户:
SELECT
USER,
CAST(ACTIVITY AS DATE),
COUNT(DISTINCT ACTIONS),
SUM(RESULTS)
FROM
TABLE a
WHERE
ACTIVITY >= DATEADD(MONTH, -6, GETDATE()) AND
EXISTS (SELECT *
FROM TABLE b
WHERE a.USER = b.USER AND
ACTIVITY >= DATEADD(MONTH, -1, GETDATE()))
GROUP BY
USER
ORDER BY
[conditions]
根据我的理解,
create table #date ( id int, logdate date)
insert #date values
(1,'2018-08-03') -- last month
, (1,'2018-05-03') -- before 4 month
, (1,'2018-03-03') -- before 6 month
, (1,'2018-02-03') -- before 7 month
, (2,'2018-09-03') -- logged on this month
, (2,'2018-05-03') -- before 4 month
, (3,'2018-07-03') -- before 2 month
select *, 'Who logged on before 6 months from last month'
from #date
WHERE DATEPART(m, logdate) <= DATEPART(m, DATEADD(m, -1, getdate())) -- logged date on last month
and DATEPART(m, logdate) >= DATEPART(m, DATEADD(m, -6, getdate())) -- logged date on before 6 months
and id in ( --
select id from #Date where DATEPART(m, logdate) = DATEPART(m, DATEADD(m, -1, getdate())) --
) -- Ids who Logged in past month
/* User 1, who logged on past month. So query gets his past 6 (3,4,5,6,7,8) month's logged date */
如果查询需要更新,请将我还原。