SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Collating Records based on Dates
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

jwm
Starting Member

USA
1 Posts

Posted - 08/12/2013 :  16:38:09  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3712 Posts

Posted - 08/12/2013 :  16:54:27  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000