Groups | Blog | Home
all groups > sql server programming > october 2007 >

sql server programming : Summing by Date into a week


Ant
10/25/2007 10:02:00 PM
Hi,
I have a table which includes a cost column & a date column. The dates are
roughly one or two days apart.
I need to sum the costs into weekly groups.

How can I do this?

Many thanks in advance for any ideas on this

Liz
10/26/2007 12:20:27 AM


[quoted text, click to view]

this should get you started:

select min(someDate), max(someDate), datepart(yy, someDate), datepart(wk,
someDate), sum(CostColumn), count(*) FROM tickets
GROUP BY datepart(yy, someDate), datepart(wk, tick_date) order by 3, 4

Be careful about week numbers at year boundaries; results may not be as you
expect

Ant
10/26/2007 1:08:00 AM
Hi Liz,

Thanks for your help with this, I've decided on your solution.
I noticed that it sometimes shows 53 weeks per year as you warned. What can
I do about this? I'm using this to compare to another table so if I used the
same query for the other tbl, will this be an issue?

Many thanks

Ant

[quoted text, click to view]
David W
10/26/2007 1:49:12 AM
SELECT Sum(MyCost), DateDiff(d, 0, MyDate) / 7

FROM MyTable

GROUP BY DateDiff(d, 0, MyDate) / 7

Replace 0 if your week starts on a different day. You won't get a row for
weeks that don't have an entry. Join to a Dates table for a more complete
solution.



Liz
10/26/2007 12:54:33 PM

[quoted text, click to view]

there will ALWAYS be 53 "weeks" per year (52 * 7 = 364); the solution
depends on what exactly the business logic requires ... you might have
another look at what David W posted and flesh it out a bit more ... you may
have preferred mine because it exposed the date boundaries but that doesn't
mean it's better, or even suitable for your requirements

as David suggested, you could work up a dates table, which might look
something like this:

CREATE TABLE weeksTable (
theDate DateTime,
xWeek int)

-- I'll leave you to figure out how to populate it but the data would look
like:

1/1/2007 1
1/2/2007 1
.....
1/8/2007 2
....
1/15/2007 3

and then JOIN it ... that way you can cut your weeks off at the end of the
calendar year or simply make them continuous regardless of year boundaries
..... again, depends on the business logic

something like this should work for the JOIN:

SELECT b.xWeek, SUM(a.Cost)
FROM myTransactions a
JOIN weeksTable b ON a.trxDate = b.theDate
GROUP BY b.xWeek

this is not a new problem; you can probably Google up a complete solution
in reasonably short order if you can't make sense of the input here ...
maybe SQLServerCentral.com has something ... good luck

L



[quoted text, click to view]

AddThis Social Bookmark Button