I have a table that is defined as follows:
CREATE TABLE [dbo].[ListingStats](
[ListingStatID] [int] IDENTITY(1,1) NOT NULL,
[StatTypeID] [int] NOT NULL,
[CreatedDate] [date] NOT NULL,
[ListingID] [int] NOT NULL,
CONSTRAINT [PK_ListingStats] PRIMARY KEY CLUSTERED
(
[ListingStatID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
I am trying to get 4 totals for each type (listingStatTypeID) for today, last 7 days, last 30 days, and all time.
I am not really sure what the most efficient query will be. Right now I have the following that I can repeat for each TYPE but that will be a big query and it will be a lot of calls.
declare @listingID int
set @listingID = 209722
--today
select count(1) from ListingStats where listingid = @listingid and CreatedDate = getdate()
--last 7 days
select count(1) from ListingStats where listingid = @listingid and CreatedDate > getdate()-7
--last 30 days
select count(1) from ListingStats where listingid = @listingid and CreatedDate > getdate()-30
--all time
select count(1) from ListingStats where listingid = @listingid
I am always calling this for one listing at a time by providing a listingID. If anyone could provide a direction I would appreciate it. Should I create a view of some sort?
Expected Results
-Type------Today-----7Days---30Days---Ever
1 44 50 500 5000
2 22 40 90 1000
3 55 55 555 5555