Monday, March 12, 2012

Generating a table from a log for past 12 months

I would like to show a datagrid where the columns are the last 12 months from whatever today is. I am drawing from what could be a rather large tagle in the DB. The Table looks like this:
LogIDLogTallyLogDateItem
1 2 3/28/03 apples
2 1 3/29/03 apples
3 2 4/01/03 oranges
4 3 4/01/03 apples
5 1 4/01/03 grapes

......

293 1 3/17/04 oranges
294 1 3/17/04 apples

And if someone wants to see a report on apples, they would see something like:
3/034/035/03..............3/04
3 3 - 3
I can select one month (this one) like this:
SELECT SUM(LogTally) AS Expr1
FROM TABLE
WHERE (MONTH(GETDATE()) = MONTH(LogDate)) AND (YEAR(GETDATE()) = YEAR(LogDate)) AND (item = 'apples')
GROUP BY item
but, I just don't know how to do it for the past 12 months. Do I play with the dates and do 12 seperate SELECTS?
THANK YOU!you could do something like:


SELECT
SUM(LogTally),
DATEPART(mm, LogDate)
FROM
YourTable
WHERE
<input criteria for last year here>
GROUP BY
DATEPART(mm, LogDate)

which should sum the values for each month.

Cheer
Ken|||Thanks for the reply.
What I need is to have each column in my datagrid to be a different month. There will always be 12 months, but there can be any amount of items(rows)
Can I do this with what you showed me?
Thanks again

No comments:

Post a Comment