SQL Server visitors by date from table?

Status
Not open for further replies.

mudboy

Ars Legatus Legionis
17,501
Subscriptor
I'm working on a web-based club membership system for the small swim club that I manage. Database is SQL Server 2012.

My table looks like this:
visitid (int, pk)
memberid (int, fk)
memberfamilyid (int, fk) (mildly redundant but stored for ease of access to data by family)
visitdatetime (datetime)
guest (bit) (members can bring guests)

If I wanted to return a result set that would have the number of visitors (memberid) and the number of guests, along with the date for each day, what might that look like?

I'm thinking this would be the output:

Code:
Date        Visits    Guests
5/25/2014   65        12
5/24/2013   38        3

Thanks,

Pete
 

Wraith

Ars Tribunus Militum
1,712
How about:
Code:
SELECT 
	DATEADD(dd, 0, DATEDIFF(dd, 0, visitdatetime )) as [Date], -- convert datetime to date only
	SUM(visitid) AS [VisitCount], -- people can visit multiple times, count each one
	SUM(guest) AS [GuestCount]
FROM
	Visit
WHERE
	visitdatetime BETWEEN @StartDate AND @EndDate
GROUP BY
	DATEADD(dd, 0, DATEDIFF(dd, 0, visitdatetime ))
ORDER BY
	DATEADD(dd, 0, DATEDIFF(dd, 0, visitdatetime )) ASC
 

wallinbl

Ars Legatus Legionis
14,332
Subscriptor
[url=http:/civis/viewtopic.php?p=26909693#p26909693:1slgief2 said:
TheBlackPenny[/url]":1slgief2]I would COUNT(guest) as well.
If guest is a bit, it's presumably 1 for guest present and 0 for no guest present. SUM() would work. COUNT() would only work if it were NULL when no guest was present, which is not how I've seen bit columns used. If you want to use COUNT(), you'd likely have to use NULLIF().

Code:
DECLARE @test TABLE (guest bit null)
INSERT @test (guest) VALUES (1)
INSERT @test (guest) VALUES (1)
INSERT @test (guest) VALUES (0)
INSERT @test (guest) VALUES (0)
INSERT @test (guest) VALUES (NULL)
INSERT @test (guest) VALUES (NULL)

SELECT SUM(CONVERT(Int, guest)) FROM @test --returns 2
SELECT COUNT(guest) FROM @test --returns 4
SELECT COUNT(NULLIF(guest,0)) FROM @test --returns 2
 

mudboy

Ars Legatus Legionis
17,501
Subscriptor
OK, this has been working fantastically. I'd like to add an hour-by-hour breakdown for each day (as a separate query). We're open from 11AM until 9PM, so I'd like to do something like this:

6/17/2014 total: 464 people

11AM-12Noon - 100
12PM-1PM - 56
1PM-2PM - 38

etc.

Is there a way to do this without using a loop and multiple queries?

Thanks,

Pete
 

fitten

Ars Legatus Legionis
55,636
Subscriptor++
You could do something like this (may not be the best example, but just illustrating):
Code:
select
	*,
	count(*)
	from
		(select
			datepart(year, DateTimeColumn) as [Year],
			datepart(month, DateTimeColumn) as [Month],
			datepart(day, DateTimeColumn) as [Day],
			datepart(hour, DateTimeColumn) as [Hour]
			from
				sometable) t
	group by
		t.[Year],
		t.[Month],
		t.[Day],
		t.[Hour]
 
Status
Not open for further replies.