SQL Server SQL条件返回HAVING

ghg1uchk  于 2023-01-20  发布在  其他
关注(0)|答案(2)|浏览(145)

我一直找不到WHEREHAVING条件来帮助我返回以下内容:
如果用户在过去一个月内记录了活动,我希望返回这些用户过去六(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)个月内,而不是当前或最近一个月。

fhg3lkii

fhg3lkii1#

您可以将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]
lvmkulzt

lvmkulzt2#

据我了解,

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                    */

如果查询需要更新,请还原我。

相关问题