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
 YTD concept

Author  Topic 

sent_sara
Constraint Violating Yak Guru

377 Posts

Posted - 2008-04-15 : 03:50:18
Hi Friends,
Can anybody help in introducing the YTD Concept:

My Table[ Monthly_Highlights_tb ] schema should contain like below:
[Month] [Base_Amount] [YTD]
APR-07 1000.00 1500.00
APR-07 500.00 1500.00
MAY-07 2000.00 3500.00
jUN-07 5000.00 8500.00

WHEN I run the below query:

UPDATE t
SET t.ytd = (SELECT SUM(q.base_amount) FROM Monthly_Highlights_tb q WHERE q.[month] = t.[month] AND q.[month] <= t.[month])
FROM Monthly_Highlights_tb t

output is coming as:
[Month] [Base_Amount] [YTD]
APR-07 1000.00 1500.00
APR-07 500.00 1500.00
MAY-07 2000.00 2000.00
jUN-07 5000.00 5000.00

cAN anybody correct the query?






SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-04-15 : 03:57:03
As said to you many many times before, ALWAYS USE PROPER DATAYPES!
We have also repeatedly asked you to supply sample data in proper format!
-- Prepare sample data
DECLARE @Sample TABLE ([Month] CHAR(6), Base_Amount MONEY, YTD MONEY)

INSERT @Sample
(
[Month],
Base_Amount
)
SELECT 'APR-07', 1000.00 UNION ALL
SELECT 'APR-07', 500.00 UNION ALL
SELECT 'MAY-07', 2000.00 UNION ALL
SELECT 'JUN-07', 5000.00

-- Do the running total update
UPDATE t
SET t.ytd = (SELECT SUM(q.Base_Amount) FROM @Sample AS q WHERE CAST('1-' + q.[Month] AS DATETIME) <= CAST('1-' + t.[Month] AS DATETIME))
FROM @Sample AS t

-- Show the result
SELECT *
FROM @Sample



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

- Advertisement -