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
 Daily totals in Column format using a Stored Proc

Author  Topic 

gualm
Starting Member

11 Posts

Posted - 2008-03-27 : 16:26:11
I am usings transact sql..

Using a stored proc. I need a generic starting point. I am trying to get order categories ie. oranges, bananas, pears on the horizontal and then the daily totals vertically for each day of the month. Just say the # under ea is the total of boxes received daily. The total under each category would be determined by the receipt date. Also
I need a total category for each fruit under each as month-date and year-to-date. This should be updated daily. Obviously my actual prog is more complicated then this but I just need an idea where to start.
Product Oranges Bananas Pears Total Fruit
03/1/08 1 2 5 8
03/2/08 0 2 1 3
03/3/08 4 0 1 5
mtd
ytd

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-03-27 : 16:27:53
Please post the DDL of your table for quick and accurate soln.
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-03-27 : 16:42:46
Something similar to

DECLARE @MOnthStart DATETIME,
@Tomorrow DATETIME,
@YearStart DATETIME

SELECT @MonthStart = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101'),
@Tomorrow = DATEADD(DAY, DATEDIFF(DAY, '19000101', GETDATE()), '18991231'),
@YearStart = DATEADD(YEAR, DATEDIFF(YEAR, '19000101', GETDATE()), '19000101')

SELECT Product,
Oranges,
Bananas,
Pears,
[Total fruit]
FROM (
SELECT CONVERT(VARCHAR(8), dt, 112) AS Product,
SUM(CASE WHEN Category = 'Oranges' THEN Items ELSE 0 END) AS Oranges,
SUM(CASE WHEN Category = 'Bananas' THEN Items ELSE 0 END) AS Bananas,
SUM(CASE WHEN Category = 'Pears' THEN Items ELSE 0 END) AS Pears,
SUM(Items) AS [Total fruit],
1 AS SortOrder
FROM Table1
WHERE dt >= @MonthStart
AND dt < @Tomorrow
GROUP BY CONVERT(VARCHAR(8), dt, 112)

UNION ALL

SELECT 'mtd' AS Product,
SUM(CASE WHEN Category = 'Oranges' THEN Items ELSE 0 END) AS Oranges,
SUM(CASE WHEN Category = 'Bananas' THEN Items ELSE 0 END) AS Bananas,
SUM(CASE WHEN Category = 'Pears' THEN Items ELSE 0 END) AS Pears,
SUM(Items) AS [Total fruit],
2 AS SortOrder
FROM Table1
WHERE dt >= @MonthStart
AND dt < @Tomorrow

UNION ALL

SELECT 'ytd' AS Product,
SUM(CASE WHEN Category = 'Oranges' THEN Items ELSE 0 END) AS Oranges,
SUM(CASE WHEN Category = 'Bananas' THEN Items ELSE 0 END) AS Bananas,
SUM(CASE WHEN Category = 'Pears' THEN Items ELSE 0 END) AS Pears,
SUM(Items) AS [Total fruit],
3 AS SortOrder
FROM Table1
WHERE dt >= @YearStart
AND dt < @Tomorrow
) AS d
ORDER BY SortOrder,
Product



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -