sqlsql-serverselecthavingsql-date-functions

SQL Conditional Return HAVING


I have been unable to find the WHERE or HAVING condition that helps me return the following:

If a user has activity logged within the past month, I want to return records for the past six (6) months for those users. I have been using the following query so far...

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]

I have attempted to use

HAVING 
    (COUNT(USER) * CAST(DATEADD(MONTH, -1, GETDATE()) AS DECIMAL)) > 0

but I am getting records returns from inactive users who have only logged action within the past six (6) months, not the current or most recent month.


Solution

  • You could use the exists operator with a subquery for the users with activity in the last month:

    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]