Dynamic Sql To Loop Over Fiscal Years
Jan 6, 2004
thanks for reading.
i'm interested in improving the format of this query. consider me clueless today, if you will. :) how can i fix this to make it dynamically move over the years? is there something i can do with set manipulation that is smarter than this?
the goal of this query is to return cases per year, where "year" is defined as (Oct 1, YYYY - Sep 30, YYYY+1) instead of the typical YYYY
problem is, i have to write it as some cludgy dynamic sql looping over an incremented year. i don't know of any other way.
again, thanks for reading ... and any help in advance.
SELECTcount(*) as 'Data Points', '2001' as 'Experiment Year'
FROM tbl_experiment_data
WHEREstart_date BETWEEN '9/30/2001' AND '10/01/2002'
and completion_date BETWEEN '9/30/2001' AND '10/01/2002'
and status = 'CaseClosed'
UNION
SELECTcount(*) as 'Data Points', '2002' as 'Experiment Year'
FROM tbl_experiment_data
WHEREstart_date BETWEEN '9/30/2002' AND '10/01/2003'
and completion_date BETWEEN '9/30/2002' AND '10/01/2003'
and status = 'CaseClosed'
UNION
...
expected output....
Data Points______ Experiment Year
32_____________ 2001
102____________ 2002
.... ....
View 4 Replies
ADVERTISEMENT
Oct 14, 2007
Hi, I would like to select data from my source system based on fiscal years. I don't want to hard code anything, e.g. select * from person where startdate > 01042005. I want to try and use a store proc or function. The main requirement is to always retrieve data from source tables for the last two fiscal years (based on todays date - getdate). Our fiscal year starts the 1st April. Therefore, If todays date is 14 October 2007, I would like to select all persons whose start date was greater than 01 April 2005. Is there an easy way to do this in sql server 2005 without hard coding dates?
Gurj
View 3 Replies
View Related
Apr 24, 2015
I need to list customers in a table that represents sales over the years.
I have tables:
Customers -> id | name |...
Orders -> id | idCustomer | date | ...
Products -> id | idOrder | unitprice | quantity | ...
I am using this SQL but it only gets one year:
SELECT customers.name , SUM(unitprice*qt) AS total
FROM Products
INNER JOIN Orders ON Orders.id = Products.idOrder
INNER JOIN Customers ON Customers.id = Orders.idCustomer
WHERE year(date)=2014
GROUP BY customers.name
ORDER BY 2 DESC
I need something like this:
customer | total sales 204 | total sales | 2015 | total sales (2014 + 2015)
--------
customer A | 1000$ | 2000$ | 3000$
customer B | 100$ | 100$ | 200$
Is it possible to retrieve these values in a single SQL query for multiple years and grand total?
View 6 Replies
View Related
Aug 23, 2005
I have a couple of servers each with around 900 databasesa and need to do indexdeframentation on them.
The loop to database and loop for tables are fine. The problem is the loop for indexes and always return -1 for @@Fetch_status after open the cur_indfetch cursor as follows
select @sqlStringField = ' DECLARE cur_indfetch CURSOR FOR ' + ' SELECT indid FROM ' + @databaseName + '.dbo.sysindexes ' + ' WHERE id = OBJECT_ID (' + '''' + @TableName + ''''+ ') and keycnt > 0'
print @sqlStringField
exec master..sp_executesql @sqlStringField
OPEN cur_indfetch
FETCH NEXT FROM cur_indfetch INTO @indid
print ' before while @@FETCH_STATUS: ' + cast(@@FETCH_STATUS as varchar(5)) + ' @indid:' + cast(isnull(@indid, 0) as varchar(5))
WHILE @@FETCH_STATUS = 0
BEGIN
print ' Cursor 3--cur_indfetch--' + @databaseName + '--@tableName:' + @tableName + '--' + cast(@indid as varchar(7))
IF @indid <> 255
begin
DBCC INDEXDEFRAG (@databaseName, @TableName, @indid)
end
FETCH NEXT FROM cur_indfetch INTO @indid
END
CLOSE cur_indfetch
DEALLOCATE cur_indfetch
any idea?
thanks
David
View 3 Replies
View Related
Nov 18, 2011
@strSql is a dynamic query in while loop which can return single record, single row of records, multiple rows of records.
So only if it returns single record then I have to store it otherwise convert to xml before storing.
1) If it returns 1 record(1row and 1 column) then save as it is.
2) if it returns a row with more than 1 columns then convert to xml before saving.
2) if it returns data rows then convert to xml before saving.
View 2 Replies
View Related
Apr 4, 2006
Hello-
I'm trying to read a table that has database connection information for other DBs and use this within an "Execute SL Task" task. I have seen a number of posts that talk about this possibility, but I have not been able to get it to work yet.
When I've tried to set the connection to a variable (@[User::DB_ConnectionStr]) in the Expressions area of the SQL Task, the Connection type defaults to OLE DB and I can't seem to force it back to ADO or ADO.net.
I've tried doing this with the variable being set to both a connection object and a String with the connection string, but neither seems to work.
Any suggestions? Should this be a string value of the connection string? Am I missing something when trying to set the connection type?
Thanks much!
Tristan
View 3 Replies
View Related
Jul 20, 2005
Hi;I would like to read a list of tables from a temp table and then do asql statement on each table name retrieved in a loop, ie:-- snip cursor loop where cursor contains a list of tablesdeclare @rec_count intset @rec_count = 0exec('select @rec_count = count(myfield) from ' + @retrievedTableName)This does not work. SQLSERVER tells me @rec_count is not declared.How can I get the @rec_count populated....or can I?Thanks in advanceSteve
View 3 Replies
View Related
Mar 28, 2008
I have a summary report that displayes data on a yearly basis. Currently I am filtering the MDX query with:
SELECT ...
FROM
( SELECT ( STRTOSET(@DateShippedYear, CONSTRAINED) ) ON COLUMNS FROM ...)
This works fine if the user wants to see the report by calander year. I am not sure what to do when the client wants to see a report by fiscal year. Each division in the company may have a different fiscal year. I have a dimension which lists division name and fiscal start month. Is there any way massage the data based on another parameter? I do something like that in other reports where I use a parameter to select how many months the user wants to display:
...
, lastperiods(@RollBackNum,STRTOMEMBER(@DateShippedYearMonth,CONSTRAINED))
In this case I would have to parce the parameter to get the month start number.
Or would I be better off filtering the data as it is returned to the table or matrix? Here is logically what I'd want to do:
IIf(Parameters!FC.Value = 2 OR Parameters!Division.Value='All'),
IIf(Fields!Year.Value=Parameters!Year.Value,"true", "false"),
IIf(Fields!Month.Value>= Code.FMonth(Parameters!Division.Value) AND Fields!Year.Value = Parameters!FYears.Value-1 OR Fields!Month.Value < Code.FMonth(Parameters!Division.Value) AND Fields!Year.Value = Parameters!FYears.Value, "true", "false"))
I don't see a place to type in a filter statement like that.......Perhaps a WITH clause in my MDX code which filters each row as "ture" or "false" based on the criteria......
View 3 Replies
View Related
Mar 13, 2007
strSQL = "SELECT DISTINCT YEAR(Date1) As Year FROM WorkShopReq WHERE Year(Date1) > 1999 ORDER BY 1"oRsYears.Open strSQL, DB_CONNECTION'If no years has been specified select the last oneIf intYear="" then While not oRsYears.EOF intYear = oRsYears("Year") oRsYears.MoveNext() Wendend if'Move to firstoRsYears.MoveFirst() The above code works and displays the data for the Years from 1999 onwards which get inserted into a drop down box in the web page from where the user selects the year and accordingly the all the data for that year displays on to the web page. * Field Date1 is smalldatetime Now I want to select the data between fiscal year. e.g. 6/1/year(date1) to 5/31/year(date1)+1 So i edit the strSQL statement strSQL = "SELECT DISTINCT YEAR(Date1) As Year FROM WorkShopReq WHERE Date1 BETWEEN 'Year(Date1)/5/31' AND '(Year(Date1)+1)/6/1' ORDER BY 1" I get this errorError Type:
Microsoft OLE DB Provider for ODBC Drivers (0x80040E07)[Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting character string to smalldatetime data type./wsr blue/Default.asp, line 24 What am i doing wrong.
View 2 Replies
View Related
Nov 29, 2006
HiI am trying to perform a search that will return records based on afiscal year search of the bill_Date. The user gives the year then Iwant to search based on the fiscal year (July 1 - June 30) for the yeargiven. The table looks like thisBill Tableid_Num bill_date bill_amount23 7/1/2005 500.0033 12/2/2005 600.0044 3/3/2006 700.00I have triedSelect Bill.id_num, Bill.bill_date, Bill.bill_amountfrom Billwhere Bill.bill_date BETWEEN 7/1/ + @year and 6/30/ + (@year +1)Plus a variety of other fruitless concoctions....but nothing seems towork. Any help would be appreciated.
View 4 Replies
View Related
May 15, 2008
Hello,
I'm having a problem with converting calender months to fiscal months.
For April (04) calender month, I have 11 as my fiscal month like below.
[FISCAL CALENDAR].[DAY].&[11]&[2008-04-15T00:00:00]
Here is a parameter 'param' which is a 'datetime' datatype, so i'm basically passing a calender date , so i wrote the query as following:
="[FISCAL CALENDAR].[DAY].&[" + (Month(Parameters!param.Value)+7).ToString + "].&[" + CDate(Parameters!param.Value).ToString("s") + "]"
But it is wrong as I get results like the following:
For April (04), I get 11, which is correct.
[FISCAL CALENDAR].[DAY].&[11].&[2008-04-15T00:00:00]
But for June (06), I get 13 when I'm supposed to get 1.
[FISCAL CALENDAR].[DAY].&[13].&[2008-06-15T00:00:00]
How do I change my query? Please help. I'm struggling with this since yesterday.
View 4 Replies
View Related
Oct 6, 2007
I have a view that shows payment amount, payment date. I need to add a column to the view that shows what fiscal year the payment belongs to.
How can this be done?
I do have a table that has the fiscal start and end in it, tblGlobal with fields FiscalYearStart and FiscalYearEnd.
View 16 Replies
View Related
Mar 17, 2014
I am using the query below and it is working great to give me montly averages. I need to find the fiscal year to date averages for the same data. I think all I should need to change is the Select and Group by sections but I am having no sucess.
SELECT Format([CallDate],"yyyy mmm") AS [Month], Count(DailyCallStats.CallDate) AS CountOfCallDate, DailyCallStats.Agent, Avg(DailyCallStats.Inbound) AS AvgOfInbound, Avg(DailyCallStats.Outbound) AS AvgOfOutbound, Avg(DailyCallStats.TotalCalls) AS AvgOfTotalCalls, Avg(DailyCallStats.AvgWrap) AS AvgOfAvgWrap, Avg(DailyCallStats.ParkTime) AS AvgOfParkTime
FROM DailyCallStats
GROUP BY Format([CallDate],"yyyy mmm"), DailyCallStats.Agent, Format([CallDate],"yyyy mm")
ORDER BY Format([CallDate],"yyyy mm");
View 4 Replies
View Related
Jul 19, 2007
I have select statement that returns data on a construction project.
I have a start date, end date, and forecasted cost for each task in the project. I need to create a table that spreads the dollars in a linear fashion broken down by fiscal period.
I have:
task_id, start_date, end_date, cost
1, 9/15/2008, 12/15/2008, 3000
2, 7/1/2008, 12/15/2008, 550
I need
task_id, fiscal_period, cost
1, 200803, 500
1, 200804, 1000
1, 200805, 1000
1, 200806, 500
2, 200801, 100
2, 200802, 100
2, 200803, 100
2, 200804, 100
2, 200805, 100
2, 200806, 50
I can do the math to properly calculate the dollar amount, I am having trouble creating the statement that will process through each row of my select statement and insert multiple rows into the new table.
View 4 Replies
View Related
Mar 18, 2008
I need to take multiple rows in a table that store fiscal data and denormalize into one row with all the fiscal information in it. any suggestions on how to approach this creatively - lots of data will make it important to make this efficent, will need to run each year so I would like to make it portable.
Fiscal data table
companycode 1 1 1
fiscalyear 2008 2008 2008
fiscalperiod 200801 200803 200802
amount 101 301 201
result set
companycode 1
fiscalyear 2008
fiscalmonth1_amount 101
fiscalmonth2_amount 201
fiscalmonth3_amount 301
fiscalmonth4_amount
..
fiscalmonth12_amount
thanks
View 6 Replies
View Related
Apr 6, 2015
I am working on creating a new report that has to get its date from several different tables. Some of these tables update at the beginning of the fiscal month, others at the beginning of the calendar month (). My goal is to develop a stored proc that will run once a month, get all the data from the various sources, and insert into a history table. An SSRS report will generate off of the data in this history table so users can see a running history of the data. I am having trouble creating a way to determine this though. Fiscal months always start on a Sunday. We have a calendar table that translates each date into the fiscal day, fiscal month, etc. Changing the legacy scripts to run on fiscal instead of calendar is not an option.
Idea 1: Wrap the script in an IF statement that will determine the date of last day of the previous calendar month, and the date of the last day of the previous fiscal month, and if current date is greater than both of those, then run the script. But this runs into issues because the current date could be in a different calendar month than fiscal month causing the idea of "previous month" to be incongruent.
Idea 2: Find the current day of year, then if this is greater than last day of the previous fiscal and calendar months, run script. Issue this this is in january, fiscal day might be 2 but calendar day might be 364, so it will never run.
View 4 Replies
View Related
Aug 19, 2014
I need a Query for calculating the fiscal_week based on the input dates (start_date and end_date), though I got a query from this forum, it is not giving me exact result.
the sample is in the excel file with the attachment.
In the excel:
First tab tells you the raw_data what I am using to find the Fiscal_week
Second tab tell you the data where i found the mistake, and how I am expecting the output.
I also have attached the query I have got from this forum, query I have modified for fiscal week.
View 4 Replies
View Related
Jun 2, 2015
I am trying to create a calculated member for Cumulative sum using Fiscal Calendar using the below code:
WITH MEMBER [Measures].[No of Accounts Cumulative]Â
AS 'Sum(PeriodsToDate([DimFinancialDate].[FiscalMonth].[(all)],[DimFinancialDate].[FiscalMonth].CURRENTMEMBER), [Measures].[No of Accounts])'
SELECT
  {[Measures].[No of Accounts],[Measures].[No of Accounts Cumulative]} ON COLUMNS,Â
  [DimFinancialDate].[FiscalMonth].Members ON ROWS
FROM [Acquisition]
where [DimFinancialDate].[Year - Â Quarter - Â Month - Â Date].[FiscalYear].&[2014-04-01T00:00:00];
Getting below OUTPUT:
No of Accounts No of Accounts Cumulative
All 1763 1763
Apr 14 116 353
May 14 30 383
Jun 14 284 667
Jul 14 112 779
Aug 14 38 817
[code]....
Basically, It is taking all the members of the Fiscal date dimension to compute the output, But what i am expecting is to compute only for Fiscal calendar that is from April 2014 - March 2015.
View 2 Replies
View Related
Jul 29, 2015
Our fiscal year starts on July 1st. Each month they call a period - so July is period 1, August is period 2, etc.
They are wanting a report that pulls numbers for a given period. There are parameters for them to select the fiscal year and the fiscal period, and then it calculates the numbers for that period. That part works fine.
Now they want me to do some calculations, and one of them is to divide one of the numbers by the # of days since the fiscal year. So if they choose July, it would be 31 days. If they choose August, it would be 61 days, etc. How can I set this up to calculate the number of days when they really aren't entering a start date, it's just a fiscal year and period.
Is there a way to calculate a date field that is 07/01/xxxx where xxxx is the fiscal year they chose? Also a way to calculate a date field that would be the last date of the month for the fiscal period and year they chose?
I suppose I could add 2 other parameters where they enter the start of the current fiscal year, and the last day of the period they're running it for, and use a datediff to calculate that. Just seems kind of redundant.
View 8 Replies
View Related
Sep 20, 2006
Hi,
Using SQL Server 2000, I need to perform date range type queries that involve my company's Fiscal Year, which is not the same as the calendar year. My company's Fiscal Year if from Sept 1 to Aug 31, where Aug 31st year determines the Fiscal Year. For example, since today's date is 09/20/2006, the current Fiscal Year is 2007.
An example of a typical query requirement:
Find all the sales figures to-date for the current Fiscal Year. So, a WHERE clause will consist of a date range query from 09/01/2006 to 8/31/2007.
Initially, I created a Function to find the current Fiscal Year based on the current date, by calling the GETDATE() function and passing the results to the following function:
CREATE FUNCTION dbo.fnGetFY (@CurrentDatetime datetime)
RETURNS int
AS
BEGIN
DECLARE @FY int
IF (SELECT MONTH(@CurrentDatetime)) > 8
SET @FY = YEAR(@CurrentDatetime) + 1
ELSE
SET @FY = YEAR(@CurrentDatetime)
RETURN(@FY)
END
So, the view queries that involve the Fiscal Year call the above function.
However, these function calls drag down the VIEW query response time to the point where the time is either unacceptable or an ODBC Timeout occurs, even with Query Analyzer.
Is there a way to create a Global server parameter to hold the current Fiscal Year value, so function calls are not necessary? Or set Fiscal Year date ranges for a database or server system parameter?
Does anyone know of a efficent, response timewise, way to handle Fiscal Year date range queries?
Will appreciate the help!!!
View 5 Replies
View Related
Nov 6, 2015
I have a table where hours are being loaded in a weekly basis. The YearWeek is populated when the data is loaded. The value format of the Year Week is 2015-39, 2015-41, etc. I need to calculate the total hours per Fiscal Year.For example, week '2015-39' will be return FY15 and week '2015-41' will return FY16, and so on. By extracting the year, I can do a group by and have total hours for each year.
Currently, I have it working by splitting the value into year and week and then looping through each year and week, so I can assign the totals to the corresponding FY.select sum(hours) as total, yearweek from tablename group by yearweek...Then I loop through using C#.I can return the FY using an actual date,how to do it for year-week format for any given year.
select CASE
WHEN CAST(GETDATE() AS DATE) >
SMALLDATETIMEFROMPARTS(DATEPART(YEAR,GETDATE()),09,30,00,000)
THEN
DATEPART(YEAR,GETDATE()) + 1 ELSE DATEPART(YEAR,GETDATE())
END AS FY
View 9 Replies
View Related
Feb 3, 2015
I'm trying to create a WHERE statement that will calculate values from our current fiscal year to the last complete month.I'm using code that was created for us that does the calculations for our entire fiscal years. I thought I had fixed the WHERE statement to work like we wanted last year, but it appears to be broken now after trying it again in January and February. I'm guessing my WHERE statement only works for March and up, but how to get it to work for every month. Most attempts I'm trying it's just returning very large and inaccurate values.
I included my WHERE statement below of what I originally had that worked last year. The @BeginYear/Month/etc are retrieved from a different table and @Month is just set to MONTH(GETDATE())-1.
WHERE
(YEAR(SA3.DocumentDate)=@BeginYear AND MONTH(SA3.DocumentDate)>=@BeginMonth AND MONTH(SA3.DocumentDate)<=@Month)
OR
(YEAR(SA3.DocumentDate)=@EndYear AND MONTH(SA3.DocumentDate)<=@EndMonth AND MONTH(SA3.DocumentDate)>=@Month)
View 6 Replies
View Related
Sep 28, 2005
Of database experience do you have?
And what are they?
View 14 Replies
View Related
May 28, 2010
difference between FOR LOOP and FOREACH LOOP with example(if possible) in SSIS.
View 4 Replies
View Related
Dec 30, 2004
I just wanted to wish everyone a Happy New Years and I wanted to thank all submitters to this forum for breaking up my code monkey workday and cutting into my productivity and I have found many of these discussions helpful in my preperation for my long procrastinated MCDBA exams.
Get hammered and do not drive.
View 2 Replies
View Related
Dec 19, 2001
--Use the following formula to calculate a person's age in years in a stored procedure,
--where @dob is the person's date of birth and @yyyymmdd is the date on which to determine the age:
DECLARE @age int
DECLARE @dob datetime
DECLARE @yyyymmdd varchar(11)
SELECT @dob = '12/06/1966'
SELECT @yyyymmdd = GETDATE()
SELECT @age = FLOOR(DATEDIFF(day, @dob, @yyyymmdd) / 365.25)
PRINT CONVERT(varchar, @age)
--Notes:
--Substitute "getdate()" for the @yyyymmdd variable if you want to determine the person's age right now.
--The function divides by 365.25 to allow for leap years and uses the FLOOR function to make sure the function returns an integer.
--The function DATEDIFF(year, @dob, @yyyymmdd) doesn't work because Microsoft chose to implement
--the "year" part of the function to calculate the number of year boundaries crossed.
View 20 Replies
View Related
Jul 20, 2005
HI all,This has puzzled me all morning. I have a int field which reads19691124 (UK dates) this is actually a date 24 November 1969 I need toadd 28 years to this making it 19971124 but I’m stumped!Any ideas anyone?CheersSean*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
View 4 Replies
View Related
Feb 22, 2006
I have a table with RowID(identity). I need to loop though the table using RowID(not using a cursor). Please help me.
Thanks
View 6 Replies
View Related
Dec 30, 2005
remember if you drink too much, get a taxi and charge it to your company.
View 4 Replies
View Related
Oct 24, 2006
Hi there.
I work for a charitable organization, am new to this form (and sql programming) and trying to create a flag for unique records indicating the number of consecutive years a donor has given.
I have create a sample db idenifying donor, giving year and total pledges with multiple donor records existing for multiple years having donated.
CREATE TABLE mygifts06 (Donor_id varchar (10), Gift_yr nvarchar (4), Tot_pledges numeric (16,2))
INSERT INTO mygifts06 (Id,Gift_yr,Pledges)
SELECT 155758,2005,15.00 UNION ALL
SELECT 155759,2004,25.00 UNION ALL
SELECT 155758,2004,40.00 UNION ALL
SELECT 155757,2005,100.00 UNION ALL
SELECT 155758,2002,30.00 UNION ALL
SELECT 155758,2001,120.00 UNION ALL
SELECT 155755,2003,15.00 UNION ALL
SELECT 155758,2006,80.00 UNION ALL
SELECT 155757,2003,65.00 UNION ALL
SELECT 155759,2005,400.00
For the above dataset, I am trying to create the following output
Donor_id 2_consec_gifts 3_consec_gifts 4 consec_gifts
--------- -------------- -------------- --------------
155755000
155757000
155758110
155759100
Do I need to use a cursor for this task? I lack experienced in using cursors is there an alternative method someone could suggest?
Thanks in advance.
View 9 Replies
View Related
Jun 23, 2008
SELECT * FROM TEST NOLOCK
WHERE FY_CD = DATEPART(YEAR, GETDATE())
This gives me last years - but they want last years 2007 and 2008
Any suggestions
View 3 Replies
View Related
Sep 30, 2014
I want an sql query that wil give me listing of 20 years from current year.
View 2 Replies
View Related
Mar 27, 2007
I have a table name employee and datetime column named dateofbirth, how can i write a select statement to show their, date of birth and age in years?
This is how i did it, i couldn't finish it, Any feedback would be very thankful.
select name, datebirth, year(dateofbirth)
from employee
View 10 Replies
View Related