Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Collating Records based on Dates

Author  Topic 

jwm
Starting Member

1 Post

Posted - 2013-08-12 : 16:38:09
I am trying to create a report where the rows of the database have fields containing customer names and dates associated with the names. I want to know for each customer how many records the customer has for specified date ranges.

SELECT [DL].[Customer], Count([DL].[Date Received]) AS [CountOfDate Received1]
FROM [DL]
WHERE ((([DL].[Date Received]) Between #12/31/2012# And #1/1/2014#))
GROUP BY [DL].[Customer];

The idea is a list of the number of records for each customer in 2013. Open to any suggestions for improvement.

Ultimately my goal is to show the customer activity over multiple years.

So,
Customer Name 2011 2012 2013
Customer A 1 2 3
Customer B 2 4 6
Customer C 5 4 3

I am trying to go down the path of a Union:

SELECT [DL].[Customer], Count([DL].[Date Received]) AS [CountOfDate 2013]
FROM [DL]
WHERE ((([DL].[Date Received]) Between #12/31/2012# And #1/1/2014#))
GROUP BY [DL].[Customer]

UNION

SELECT [DL].[Customer], Count([DL].[Date Received]) AS [CountOfDate 2012]
FROM [DL]
WHERE ((([DL].[Date Received]) Between #12/31/2011# And #1/1/2013#))
GROUP BY [DL].[Customer]

UNION
SELECT [DL].[Customer], Count([DL].[Date Received]) AS [CountOfDate 2011]
FROM [DL]
WHERE ((([DL].[Date Received]) Between #12/31/2010# And #1/1/2012#))
GROUP BY [DL].[Customer];

This returns 2 columns only not the four I am looking for.

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-12 : 16:54:27
Do just one query and group it by year:
SELECT  [DL].[Customer] ,
YEAR([DL].[Date Received]) AS [Year] ,
COUNT([DL].[Date Received]) AS [CountOfDate Received1]
FROM [DL]
GROUP BY [DL].[Customer] ,
YEAR([DL].[Date Received]);
If you then want to get it in a pivoted form, use the pivot operator like shown below:
SELECT * FROM (      
SELECT [DL].[Customer] ,
YEAR([DL].[Date Received]) AS [Year] ,
COUNT([DL].[Date Received]) AS [CountOfDate Received1]
FROM [DL]
GROUP BY [DL].[Customer] ,
YEAR([DL].[Date Received])
) s
PIVOT (SUM([CountOfDate Received1]) FOR [Year] IN ([2011],[2012],[2013]))P
Go to Top of Page
   

- Advertisement -