Click here to Skip to main content
16,016,557 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hi,
I have table structure in Sql Server as below

SQL
Table - VisitorHits
VisitorId (int-IDENTITY(1,1)) (Primary Key)
VisitorDate (date) (Unique)
Hits (int) (default 0)



I have hits for different unique date in this table of my website, I have admin panel and I want to show following details
Total Visitors, Visitors This Month, Visitor Today

I want to make Select Query such that the data will be fetch as follow



SQL
TotalVisitor | VisitorThisMonth | VisitorToday
92373        | 46350            | 4045


How can I achieve this row using single query
I know that,
first result will be Sum of Hits in table
second result will be count of hits of rows where month is same as current
third result will be Hits of current day.

But I need all this thing in single row.
Please help me in generating query.
Thanks :)
Posted

Try:
SQL
SELECT SUM(Hits) AS TotalVisitor,
       SUM(CASE WHEN DATEDIFF( m, VisitorDate, GETDATE() ) = 0 THEN 1 ELSE 0 END) AS VisitorThisMonth,
       SUM(CASE WHEN DATEDIFF( d, VisitorDate, GETDATE() ) = 0 THEN 1 ELSE 0 END) AS VisitorToday
FROM VisitorHits
 
Share this answer
 
Comments
amit Baswa 14-Dec-13 4:50am    
Hi, Above query worked for me, but need some correction in above query as follow
SELECT
SUM(Hits) AS TotalVisitor,
SUM(CASE WHEN DATEDIFF( m, VisitorDate, GETDATE() ) = 0 THEN Hits ELSE 0 END) AS VisitorThisMonth,
SUM(CASE WHEN DATEDIFF( d, VisitorDate, GETDATE() ) = 0 THEN Hits ELSE 0 END) AS VisitorToday
FROM VisitorHits
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900