Question

I not sure is this correct, anyone can guide me on this. I trying to retrieve my number of guest sign in per day for a period of 1 month but there bound to some empty count where no one sign in. So the result will be like

DATE        |        COUNT
2013-12-01            2
2013-12-05            4

But what i wanted is

DATE        |        COUNT
2013-12-01            2
2013-12-02            0
2013-12-03            0
2013-12-04            0
2013-12-05            4

so i found on this website is to use recursive date generating then logically i thought of select the end result of the date and join with my member select.

DECLARE @startDate DATE
DECLARE @endDate DATE

SET @startDate = '2013-12-01'
SET @endDate = '2014-01-01'
;
WITH dates(Date) AS 
(
    SELECT @startdate as Date
    UNION ALL
    SELECT DATEADD(d,1,[Date])
    FROM dates 
    WHERE DATE < @enddate
)

SELECT dates.Date, COUNT(Guest.Identity)
FROM [Membership].[dbo].[Guest] 
right join 
dates 
on
Dates.Date = Guest.SignInDateTime and 
Guest.SignInDateTime >= @startdate and
Guest.SignInDateTime < @enddate and
DATEPART(hh, Guest.SignInDateTime) >= 10 and 
DATEPART(hh, Guest.SignInDateTime) <= 13
GROUP BY DATEPART(d, dates.Date) 
ORDER BY dates.Date asc

But i face with error like dates.Date is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Anyone can guide me on this or have better way of doing it? Thanks in advance

Was it helpful?

Solution

You are grouping by DATEPART(d, dates.Date) but selecting dates.date. I think you want something like this:

SELECT DATEPART(d, dates.Date), COUNT(Guest.Identity)
FROM [Membership].[dbo].[Guest] 
    right join dates on
        Dates.Date = Guest.SignInDateTime and 
        Guest.SignInDateTime >= @startdate and
        Guest.SignInDateTime < @enddate and
        DATEPART(hh, Guest.SignInDateTime) >= 10 and 
        DATEPART(hh, Guest.SignInDateTime) <= 13
GROUP BY DATEPART(d, dates.Date) 
ORDER BY DATEPART(d, dates.Date) asc

Relooking over your sql, assuming SignInDateTime contains a timestamp, then this query might not return your desired results since Dates.Date is just a date. Perhaps you're actually looking to join on just the date (and as Gordon pointed out, group by the dates.date):

SELECT dates.Date, COUNT(Guest.Identity)
FROM Dates left join [Membership].[dbo].[Guest] on
        Dates.Date = cast(Guest.SignInDateTime as date) and 
        Guest.SignInDateTime >= @startdate and
        Guest.SignInDateTime < @enddate and
        DATEPART(hh, Guest.SignInDateTime) >= 10 and 
        DATEPART(hh, Guest.SignInDateTime) <= 13
GROUP BY dates.Date
ORDER BY dates.Date asc

OTHER TIPS

Change the group by to:

GROUP BY dates.Date

You probably don't want to group by the day of the month anyway. The full date is more useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top