Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you want to count for the last 7 days and the last 30 days, you could use something like this:</p> <pre><code>-- Count of Participants in the last 7 days SELECT COUNT(DISTINCT Q.UserName) FROM dbo.UserQuiz Q WHERE DateTimeComplete &gt;= DATEADD(dd, -7, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) -- Count quizzes taken in the last 7 days SELECT COUNT(Q.QuizID) FROM dbo.UserQuiz Q WHERE Q.DateTimeComplete &gt;= DATEADD(dd, -7, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) -- Count quizzes taken in the last 30 days SELECT COUNT(Q.QuizID) FROM dbo.UserQuiz Q WHERE Q.DateTimeComplete &gt;= DATEADD(dd, -30, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) </code></pre> <p>Note that if you want to count for calendar weeks and calendar months then you need to do a bit more work to filter the proper starting and ending date filters.</p> <hr> <p><strong>EDIT:</strong> Fixed the query syntax (1st answer posted without running it in SSMS) also I didn't notice at first that the UserQuiz.UserQuizID is nullable. This column is therefore not what I would have expected it to be. </p> <hr> <p><strong>EDIT #2:</strong> As per OP's request, these three statistics can also be retrieved in a single query using sub-selects. Sub-selects are necessary because of differences in either the filter criteria or the aggregations involved in counting each statistic (or both).</p> <pre><code>-- Combine three stats into one query using sub-selects... SELECT (SELECT COUNT(DISTINCT Q.UserName) FROM dbo.UserQuiz Q WHERE DateTimeComplete &gt;= DATEADD(dd, -7, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))) as ParticipantsLast7Days, (SELECT COUNT(Q.QuizID) FROM dbo.UserQuiz Q WHERE Q.DateTimeComplete &gt;= DATEADD(dd, -7, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))) as QuizzesLast7Days, (SELECT COUNT(Q.QuizID) FROM dbo.UserQuiz Q WHERE Q.DateTimeComplete &gt;= DATEADD(dd, -30, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))) as QuizzesLast30Days </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload