SQL有条件返回

时间:2018-09-02 17:25:22

标签: sql-server conditional sql-date-functions

我无法找到可以帮助我返回以下内容的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)个月内记录了操作,而不是当前或最近一个月。

帮助?!

预先感谢

2 个答案:

答案 0 :(得分:0)

您可以对上个月有活动的用户使用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]

答案 1 :(得分:0)

据我了解

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

如果需要更新查询,请回复我。