1

Hi I have a query like this which returns enrollment data for the past 6 months, however data will only be display should there be at least 1 enrollment, how can display the months which have no enrollment as well? I know I probably have to do something to this line:

LEFT(CONVERT(varchar, issuedate, 112), 6) BETWEEN 
   LEFT(CONVERT(varchar, DATEADD(MM, -6, GETDATE()), 112), 6) AND 
   LEFT(CONVERT(varchar, GETDATE(), 112), 6)

Thanks.

SELECT 
    DateName(month,issuedate) + ' ' + CAST(Year(issuedate) as Char(4)) as IssueDate,
    COUNT(distinct m.ID) AS SignUps
FROM
    Member m 
INNER JOIN 
    Card c ON m.ID = c.MemberID
WHERE 
    m.Deletedby is null 
    AND c.Deletedby is null
    AND LEFT(CONVERT(varchar, issuedate, 112), 6) BETWEEN   
            LEFT(CONVERT(varchar, DATEADD(MM, -6, GETDATE()), 112), 6) 
            AND LEFT(CONVERT(varchar, GETDATE(), 112), 6)
 GROUP BY 
    DateName(month, issuedate) + ' ' + CAST(Year(issuedate) AS  Char(4)), CAST(CAST(YEAR(issuedate) AS VARCHAR) + '/'+ CAST(MONTH(issuedate) AS VARCHAR) +'/1' AS DateTime)
1
  • Wouldn't simply removing that condition accomplish what you want? Commented Dec 28, 2011 at 8:08

1 Answer 1

2

Observations:
1. table names don't imply how they are connected.
2. using functions like you have used will never use right indexes.
3. all column references should be qualified by table aliases, to make the code easy to understand.
4. getdate() is a non-deterministic function and causes bad query plan. Pass date into the sp.

Assuming that a entry in Card table is created when some member enrolls for the card:-

SELECT 
    <month_year_string> as IssueDate,
    COUNT(distinct c.memberid) AS SignUps
FROM
    Member m 
lEFT OUTER JOIN 
    Card c ON m.ID = c.MemberID     AND c.Deletedby is null
WHERE 
    m.Deletedby is null 
    AND c.issuedate BETWEEN  DATEADD(MM, -6, GETDATE()) AND GETDATE()
 GROUP BY <month_year_string>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the pointers but it doesn't solve my problem of showing null data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.