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
 Sum by Week, Month, Quarter, Year
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

caoneill
Starting Member

10 Posts

Posted - 08/20/2014 :  10:55:08  Show Profile  Reply with Quote
Hi all,

I am trying to group counts by week,month,quarter, year for a particular activity type and I'm having issues.

Here's my code so far:

SELECT
distinct
EmailAddressID,
emailaddress,
SUM(CASE WHEN [ActivityDate] >= DATEADD(WEEK, DATEDIFF(WEEK, 0, @DT), 0)
THEN
SUM(CASE WHEN EmailActivityType = 'OPEN' THEN 1 ELSE 0 END) END AS WeekTotalOpens
FROM EmailActivity
WHERE DATEPART(YEAR, [ActivityDate]) = DATEPART(YEAR, @DT)
GROUP BY EmailAddressID,emailaddress

Desired Output:

EmailAddressId EmailAddress WeekTotalOpens MonthTotalOpens etc. then WeekTotalClicks and so on....

SQL doesn't seem to like the sub-aggregate. What is the best way to approach?
Thanks so much!

caoneill
Starting Member

10 Posts

Posted - 08/20/2014 :  11:23:38  Show Profile  Reply with Quote
I figured it out..

SELECT
EmailAddressID,
emailaddress,
SUM(CASE WHEN [ActivityDate] >= DATEADD(WEEK, DATEDIFF(WEEK, 0, @DT), 0)
THEN CASE WHEN EmailActivityType = 'OPEN' THEN 1 ELSE 0 END END) AS WeekTotalOpens,
SUM(CASE WHEN [ActivityDate] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, @DT), 0)
THEN CASE WHEN EmailActivityType = 'OPEN' THEN 1 ELSE 0 END END) AS MonthTotalOpens,
SUM(CASE WHEN [ActivityDate] >= DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @DT), 0)
THEN CASE WHEN EmailActivityType = 'OPEN' THEN 1 ELSE 0 END END) AS QuarterTotalOpens,
SUM(CASE WHEN [ActivityDate] >= DATEADD(YEAR, DATEDIFF(YEAR, 0, @DT), 0)
THEN CASE WHEN EmailActivityType = 'OPEN' THEN 1 ELSE 0 END END) AS YearTotalOpens
FROM EmailActivity
WHERE DATEPART(YEAR, [ActivityDate]) = DATEPART(YEAR, @DT)
GROUP BY EmailAddressID,emailaddress
Go to Top of Page

khtan
In (Som, Ni, Yak)

Singapore
17661 Posts

Posted - 08/20/2014 :  23:12:16  Show Profile  Reply with Quote
you can use AND condition instead of nested CASE WHEN . . it will give you less headache looking at the query

	SUM(CASE WHEN [ActivityDate] >= DATEADD(WEEK, DATEDIFF(WEEK, 0, @DT), 0)
		 AND  EmailActivityType = 'OPEN' THEN 1 ELSE 0 END) AS WeekTotalOpens,



KH
Time is always against us

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