473,770 Members | 2,096 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Compare given period in current year / previous year

Hi
I want to write a function that can return a sum for a given date
range. The same function should be able to return the sum for the same
period year before.

Let me give an example:
The Table LedgerTrans consist among other of the follwing fields
AccountNum (Varchar)
Transdate
AmountMST (Real)

The sample data could be
1111, 01-01-2005, 100 USD
1111, 18-01-2005, 125 USD
1111, 15-03-2005, 50 USD
1111,27-06-2005, 500 USD
1111,02-01-2006, 250 USD
1111,23-02-2006,12 USD

If the current day is 16. march 2006 I would like to have a function
which called twice could retrive the values.
Previus period (for TransDate >= 01-01-2005 AND TransDate <=
16-03-2005) = 275 USD
Current period (for TransDate >= 01-01-2006 AND TransDate <=
16-03-2006) = 262 USD
The function should be called with the AccountNum and current date
(GetDate() ?) and f.ex. 0 or 1 for this year / previous year.
How can I create a function that dynamically can do this ?

I have tried f.ex. calling the function with
@ThisYear as GetDate()
SET @DateStart = datepart(d,0) + '-' + datepart(m,0) +
'-'+datepart(y,@T hisYear)
But the value for @dateStart is something like 12-07-1905 so this
don't work.

I Would appreciate any help on this.
BR / Jan

Mar 15 '06 #1
3 16516
(ja**********@h otmail.com) writes:
Let me give an example:
The Table LedgerTrans consist among other of the follwing fields
AccountNum (Varchar)
Transdate
AmountMST (Real)

The sample data could be
1111, 01-01-2005, 100 USD
1111, 18-01-2005, 125 USD
1111, 15-03-2005, 50 USD
1111,27-06-2005, 500 USD
1111,02-01-2006, 250 USD
1111,23-02-2006,12 USD

If the current day is 16. march 2006 I would like to have a function
which called twice could retrive the values.
Previus period (for TransDate >= 01-01-2005 AND TransDate <=
16-03-2005) = 275 USD
Current period (for TransDate >= 01-01-2006 AND TransDate <=
16-03-2006) = 262 USD
The function should be called with the AccountNum and current date
(GetDate() ?) and f.ex. 0 or 1 for this year / previous year.
How can I create a function that dynamically can do this ?


I'm uncertain on want interface you want on your function (and I am
not sure that you should use a function anyway), but here is a
query for the task:

SELECT AccountNum, LastYearTrouble s =
SUM(CASE WHEN Transdate BETWEEN
dateadd(YEAR, -1,
convert(char(4) , @date, 112) + '0101')) AND
dateadd(YEAR, -1, @date)
THEN AmountMST
ELSE 0
END),
ThisYear =
SUM(CASE WHEN Transdate BETWEEN
convert(char(4) , @date, 112) + '0101')) AND
@date)
THEN AmountMST
ELSE 0
END)
FROM Ledger
WHERE TransDate BETWEEN dateadd(YEAR, -1,
convert(char(4) , @date, 112) + '0101')) AND
@date
GROUP BY AccountNum

As for the date conversion, format 112 is essentail for playing with
dates. This format is YYYYMMDD, and this is one of the formats that
always converts back to date in the same way.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Mar 15 '06 #2
Hi There

Thank you very much. I modified your query a lillte bit, and it worked
as wanted in the function.

CREATE FUNCTION GuruInvoicedPer iodNew (@AccountNum as
VarChar(10),@Pe riod AS Int, @ThisY as DateTime)
RETURNS Float AS
BEGIN

DECLARE @LedgerTrans AS Float
SET @LedgerTrans = 0

IF @Period = 0 /*this year*/
BEGIN
SELECT @LedgerTrans =
SUM(AmountMST) FROM dbo.LedgerTrans
WHERE (DATAAREAID = dbo.GuruDataAre a())
AND (TransDate >= (convert(char(4 ), @ThisY, 112) + '0101')
AND TransDate <= @ThisY)
AND AccountNum = @AccountNum
END

IF @Period = 1 /*previous year*/
BEGIN
SELECT @LedgerTrans = SUM(AMOUNTMST) FROM dbo.LEDGERTRANS
WHERE (DATAAREAID = dbo.GuruDataAre a())
AND Transdate >= (dateadd(YEAR, -1, convert(char(4) , @ThisY,
112) + '0101'))
AND TransDate <= dateadd(YEAR, -1, @ThisY)
AND AccountNum = @AccountNum
END

RETURN @LedgerTrans
END
BR/Jan

Mar 16 '06 #3
(ja**********@h otmail.com) writes:
Thank you very much. I modified your query a lillte bit, and it worked
as wanted in the function.

CREATE FUNCTION GuruInvoicedPer iodNew (@AccountNum as
VarChar(10),@Pe riod AS Int, @ThisY as DateTime)
RETURNS Float AS
BEGIN


Yellow alert! How are you going to use this function? If you are going
to say something like:

SELECT AccountNum, dbo.InvoicedPer iod(AccountNum, 1, getdate()),
dbo.InvoicedPer iod(AccountNum, 0, getdate())
FROM accounts

It's not going to perform well. Scalar UDFs is something you should use
with care, and not the least scalar UDFs that perform table access.
There is quite an overhead for calling a UDF once per row, and when you
do table access, you have essentially created a disguised cursor.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Mar 16 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
7929
by: www | last post by:
Hi there, I need to calculate working days for a given period, "Date from", "Date To". Plus I want to be able to insert Public Holidays to exclude aswell. Your help will be greatly appreciated. Cheers Charles
1
4058
by: Terencetrent | last post by:
I have created a query that examines qarterly sales for 5 regions in the country. The query contains data for the past 6 quarters for each region and calculates the perecentage of total sales for the quarter fo each region. To help enhance the report I would love to include a comparison to of current sales to previous quarter sales and a comparison of current sales to sales a year ago. I am having a devil of a time creating a query to...
2
3565
by: Bernd Hohmann | last post by:
Dear collegues, small query problem. A table (simplified example)... customer as char(5) inv_date as date amount as double
4
10542
jiffylube
by: jiffylube | last post by:
I'm putting together a retail comp report that compares the current day stats to the same day, previous year. Is there a code I can use to get last year, same day? For example: This year stats= 7/22/2007-Sunday Previous year= 7/23/2006-Sunday I need to be able to put this string into the design view in a criteria field. For Calendar comp I use the following. This year:...
3
4870
by: Johan Mcgillicutty | last post by:
Could use some help on this one- I’m new to MS Access, and even newer to SQL. I’m building a database for clients of a treatment center, and need to keep track of when people are due for their annual physical. As near as I can tell, the simplest way to do this is to simply record when the physical was, and build a query to compile a list of all the entries from the current month, one year ago. This would enable a report to be created with...
1
4621
by: craigfr | last post by:
I want to create a graph (automatically in a report) which compares the current year's values to the previous years by plotting two lines on one chart. I have one table which has the fields: Date and DeckDefects (which is a number) I would like the X axis to show months and the Y axis to show # of DeckDefects
4
11207
by: shilpareddy2787 | last post by:
Hello, I have some total values, I want to calculate percenatge of these Total Values. I want to divide the total with No. Of working Days Excluding Saturdays and Sundays in a given period. How to calculate the Total Number of working Days in a given period . Let us say If i give the period as 08/01/2008 to 08/15/2008, I want total number of working days as 11. Please help me
7
6221
by: beaudreaux | last post by:
I am needing to calculate a month to date for the previous year in a report. Example: today is 02/18/10 and I have a month to date for today(current year). I need the report to also show month to date for 02/18/09. I believe I would be able to manipulate my current formula that figures the month to date for the current year, but I have been unsuccessful so far. I have the current year, month to date formula of: =DAvg("","","Date Between #" &...
1
5506
by: popovaa | last post by:
Hi: i need to get data for a time frame in a current year and same time frame in previous year. i found the below on this site which is almost what i need but i also need help on how to adjust the code if a have parameters @Start_Date and @End_Date (these are obviously the beginning and the end of the time frame). Also, i would like the date to be entered in MM/DD/YYYY format and not the YYYYMMDD. This is somewhat urgent request. If someone...
0
10260
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10101
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6712
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.