I am doing monthly reporting for whole months, all starting on the 1st of each month and finishing on the last day of the month
I use dateAdd to calculate the end of the month - so I add 1 month and subtract 1 second (start time is always 00:00:00).
--dFrom is Jan 01 2008 00:00:00
select @dTo=dateadd(ss,-1,dateadd(mm,1, @dFrom))
when I print dTo it is not Jan 31 2008 23:59:59 but Feb 01 2008.
Why is this?
Only starts to behave when I set the number of seconds I am adding from -1 to -31.
Time of date is unimportant: as storing all dates as midday (any data type which ONLY supports date? not interested in the time really).
Subtracting one minute from midnight works fine, but that said: I am curious to understand why I am getting the funny behaviour above.
To set up the problem, paste this into QA:if exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[WorkOTRate]') and OBJECTPROPERTY(id, N'IsUserTable')= 1)drop table [dbo].[WorkOTRate]GOCREATE TABLE [dbo].[WorkOTRate] ([TimeFrom] [smalldatetime] NOT NULL ,[TimeTo] [smalldatetime] NOT NULL ,[RateMultiplier] [float] NOT NULL) ON [PRIMARY]GOINSERT INTO dbo.WorkOTRate (TimeFrom, TimeTo, RateMultiplier)VALUES ('18:00:00', '23:59:59', 1.2)SELECT TimeFrom, TimeTo, RateMultiplier FROM dbo.WorkOTRateThis gives the following result:1900-01-01 18:00:001900-01-02 00:00:001.2So, it's storing the time 23:59:59 as midnight. That's odd.(NOTE: If you rescript the table using datetime instead ofsmalldatetime types, the data are stored correctly.)It gets worse (or better, if you like perversity).If I go to Enterprise Manager, right-click on WorkOTRate and select"Open Table" -> "Return All Rows" I get:01/01/1900 18:00:0002/01/19001.2So, I bite the bullet and change the two column types to datetime,clear out the old data and run the INSERT again. The data looks betternow.Go back to the view in EM.If I put the cursor in a new row, and type into the TimeFrom column18:30:00 and the TimeTo column 19:30:00 and the RateMultiplier column1.3, and refresh the data by pressing the red shriek !, I get this:01/01/1900 18:00:0001/01/1900 23:59:591.218:30:0019:30:001.3If I re-run the SELECT from the QA, I get this:1900-01-01 18:00:00.0001900-01-01 23:59:59.0001.21899-12-30 18:30:00.0001899-12-30 19:30:00.0001.3Is it just me, or does this seem to be remarkably inconsistent?Edward
Does any one know how I can use DATEADD and COVERT in the same select statement for retrieving data from a smalldatetime field?
I’m using ASP3.JS and MS-SQL db for a web based project
I want to retrieve a date, add a year to it, then convert it to dd/mm/yyyy format without the time showing. It works seperatly EG: convert date - SELECT adId, CONVERT(CHAR(11),datefrom,103) AS datefrom1 FROM ... Add date - SELECT adId, DATEADD(year, 1, datefrom) AS datefrom FROM....
How do you combine the 2 statements? I have been going slowly mad trying to figure this out
Hello...I am running into a problem while running a query..can some1 help..this is the query :**************SELECT *from Table Swhere S.dtDate1 BETWEEN dateadd(year,1,dateadd(month,-1,getdate()))AND dateadd(day,-1,(dateadd(month,1,dateadd(year,1,dateadd(month,-1,getdate())))))***************(first part of the date calculation comes out to be '2005-05-01' andsecond part is '2005-05-31')Here is the interesting twist:The query runs right if the first date in the between clause isentered directly i.e. the query wud run right if i rite it asSELECT *from vCustomerProductDetail Swhere S.dtDate1 BETWEEN '2005-05-01'AND dateadd(day,-1,(dateadd(month,1,dateadd(year,1,dateadd(month,-1,getdate())))))The funny part is the ending date in the between part is depending onthe starting date if u notice..so if there is somethg rong in thefirst part there shud be somethg rong with the second too if u get wati am saying but the query runs right with the second part left as itis..can some1 please help..thanks-Raghu
I need to create a user defined function to calculation the difference between today and a future date. The result needs to be in days, hours, and minutes formatted as per the following example: 1d / 4h / 30m. I have a moderate level of SQL exprience. however, I would appreciate some expert advice as the best way to approach this.
hello everyone, I have a problem of calculating a date, for example, how do i find out the begining date of the week and ending date of the week for certain date, and how do i find out the beginning date of the month and end date of the month for a certain date, thanks
Hi All! I need a query to find all dates from today to one-year back. If I start from today day I need find all dates until 11/12/98. Thanks a lot. Greg.
1. I have data something like this: start 07.30 end 16.00 How can i count how many hours and minutes from start to end?
2. Another data start: 20050805 -> August 5, 2005 end: 20050810 How can I return value that when i insert 20050809 it is between start and end, and if 20050811 it will say false that the date is between start and end
Can someone please guide me how to extract this particular data. It is quite complex, the raw data is not in a good shape and I am not sure if it is even possible. For simplification, I am copying a sample of only 3 columns from my table.
From and to date represent a duration of an event, but in some instances the data has multiple lines but they are all to be considered one event. For example all the from dates (row 1 to 8) in Oct 06 are covered by ID/row 05 because 6/9/06 to 6/12/06 is one event, all other rows of June 06 data are just redundant and not needed in the resultset. There isn't a unique event name either so comparing and picking row 05 just based on the above data is an issue. Another problem is for example the dates in October (10/5 - 10-16) all represent 1 event but the date span is spread all over. Multiple events are also possible in one month, so gettign MIN and MAX based on the month will not work.
The desired result set need to have duration of each unique event for example (1 in June, 1 in August, 1 in Sept, and 1 in Oct) and also need to have the number of events after that date and the calculated from and to date of that event:
ID FromDate ToDate Events after this date NextEventFromDate NextEventToDate 05 06/09/2006 06/12/2006 4 08/30/2006 09/05/2006 09 08/30/2006 09/05/2006 3 0913/2006 09/26/2006 13 09/13/2006 09/26/2006 2 10/05/2006 10/16/2006 ? 10/05/2006 10/16/2006 1 10/20/2006 10/25/2006 ? 10/20/2006 10/25/2006 0
I have a table that hold a couple of fields. STARTDATE - The day the service starts FREQTYPE - This field tells me how often a schedule occurs. Here are the vaules -1=oncall, 0=days, 1=weeks, 2=months FREQPERIOD - This is the number of days, weeks, or months between services. a value of -1 would indicate being oncall. DayOfWeek, Day of week for week or month-based frequencies 0=sunday 6=saturday -1=if on call WEEKOFMONTH - week of month for month based frequencies 1-4, value of 5 if it the last week of the month,
So what I need is for this report to look at the start date then figure out what the frequency is (days, weeks, months) then look at the frequency period (how many days are between services) what day of the week it falls on and list each service date on a report. There is an example at the bottom I have tried numerous things and I can't get it and I need this asap today. I can provide what ever anybody needs, Many thanks.
Here is sample data with the relationships http://www.balzoutonline.com/reporting/database.jpg
Here is the service table schema http://www.balzoutonline.com/reporting/service.jpg
Here is the serviceinfo table schema http://www.balzoutonline.com/reporting/serviceinfo.jpg
Here is the serviceschedule table schema http://www.balzoutonline.com/report...iceschedule.jpg
And here is the site table schema http://www.balzoutonline.com/reporting/site.pdf
Here is something that was created in excel wich is pretty easy but a manual process. This is what I would like to replicate in crystal http://www.balzoutonline.com/reporting/Schedule.xls
I created a Year To Date Calculation via the Buisness Intellligence Wizard. The Script is as follows:
( [Acctg Date].[Acctg Time Acctg Date Calculations].[Year to Date], [Acctg Date].[AcctgYear].[AcctgYear].Members ) = Aggregate( { [Acctg Date].[Acctg Time Acctg Date Calculations].DefaultMember } * PeriodsToDate( [Acctg Date].[Acctg Time].[AcctgYear], [Acctg Date].[Acctg Time].CurrentMember ) )
Now I'd like to edit it so that it produces "Inception To Date" to date ("Inception To Date" picks up all amounts from the beginning which in my case is 2002, as opposed to Year To Date which is from the beginning of the year).
To change to Inception To Date can I change the PeriodsToDate function to:
Hi, How can i calculate the date out? i am using vb sql server database...db saved my date as dd/MM/yyyy, form display my date as dd/MM/yyyy too 1.I have a selected date by user from calendar in tb_dop.text 2.creditDate.text for user to enter number of days to add to tb_dop.text date 3.dDate.text to display the calculated date Private Sub Calendar1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Calendar1.SelectionChanged 'display selected date from calendar tb_dop.Text = Calendar1.SelectedDate() End SubPrivate Sub btn_add2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_add2.ClickDim myDate As New DateTime myDate = tb_dop.Text Dim i As Integer i = creditDate.TextDim dDate As New DateTime dDate = myDate.AddDays(i) dueDate.Text = dDate ERROR The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value.The statement has been terminated. I know it is becos diff format of date calculation, there4, how can i change it to calculate in mm/dd/yyyy format? Funny rite? i can saved and display in dd/MM/yyyy but i cant calculate using this format Note: i cant change my form display format to mm/dd/yyyy cos i need it to be user friendly in my country ty (URGENT) Once again thanks
1)Where do I do the dateDiff calculation, at report or cube level? 2)How do I work out which dates belong to the above groups? I'm assuming i have to check if the dateDiff lies between those numbers?
I have some location assignment data that I need to convert. I need to know how long each account spent in a certain location for each month of it's overall startdate/enddate period.
E.g. Account 1 stayed in USA for 31 days in January, and 15 days in February. Account 1 stayed in UK for 13 days in February and 26 days in March. Etc.
create table #temp(account int, loc varchar(10), startdate datetime, enddate datetime) insert into #temp select 1,'USA','2014-01-01','2014-02-15' insert into #temp select 1,'UK','2014-02-16','2014-03-26' insert into #temp select 1,'AU','2014-03-27','2014-06-07' insert into #temp select 2,'UK','2014-08-15','2014-09-01' insert into #temp select 2,'AU','2014-09-02','2014-10-17' select * from #temp drop table #temp
Hi experts,I am working on SQL server 2005 reporting services and i am getting aproblem in writting a query.Situation is given below.There is one table in database Named ChildNow i have to find the All childrens whoes Age is 13 years Base onSome given parameter.If User select Augus 2007 then It has to calculate the Childs who bornin August 1994 And if he select September Then queryshould show only those child Who born in September 1994 and soon..... And use can select another year month also likeAugust 2009 ...I am writting the following querySelect Child_Name, DOb from Childwhere ((CONVERT(DateTime, A.Date_Of_Birth, 103) >= @ Parameter1And (CONVERT(DateTime, A.Date_Of_Birth, 103) <= @Parameter2)If i know already month and year then i can write easily parameter1and parameter2 But since these are comming from user so i m notfinding how to handle this.Now please suggest me what i have to write in Where statement I thinka lot but not getting any idea about it.Any help wil be appriciated.RegardsDinesh
I've read this file in PowerPivot and I need to calculate the time in weeks between the two dates for the same JO, Candidate and when the to_StatusId = From_StatusID. In other words, the number of weeks that took from going From Status "1" to Status "2".
Is it possible to do something like this using DAX? Do I need to create a calculated Column?
I’m using DAX to calculate the prior MTD count of a specific column. My data ends on 2/8/2013 and that day's PriorMTD is incorrectly corresponding to 1/31/2013. Whereas, the previous 7 days in February correctly match their corresponding January dates..Below is an image of my pivot table and I have outlined the values in red that are in question.Below are my DAX formulas used each column visible in my image:
Distinct Count of Events:=DISTINCTCOUNT([EventID])CurrentMTD:=CALCULATE([Distinct Count of Events], DATESMTD(Events[EventDate]), ALL (dimDate) )PriorMTD:=CALCULATE([Distinct Count of Events], DATEADD(DATESMTD(Events[EventDate]), -1, MONTH), all(dimDate)) ParallelMonth:= CALCULATE ([Distinct Count of Events], ParallelPeriod(Events[EventDate], -1, MONTH), ALL(dimDate))
I have a fact table with sales data at line item level, meaning lots of rows with sales orders, revenue etc. per product group pr month. Then I have a budget table with the budgetted revenue pr product group pr month, meaning a lot less detailed. I followed the method at daxpatterns.com/budget-patterns/Â with the headline "Complete pattern" to make it work. Now I have a working data model where I can see actual and budget as seperate values.
I then need to calculate the actual revenue month to date and the budgetted revenue month to date. For actual it has worked fine by doing:
The problem occurs for me doing the same on the budget figure. Since I don't have a budget per day, but only at "YearMonth" level, I have calculated the amount of workdays per month and then used the DatesMTD formula to get the cumulative workdays during the month. Furthermore I calculated the total amount of workdays in the month and made a ratio between this figure and the cumulative workdays so I get a figure in percent that tells me per day how much of the month that has went by (0-100 %). I would then multiply this percentage with the budget and get the budget month to date. This does not work since my budget figure is not at day level.
How I can get it to work. My desired result will be all the dates during a month in my rows and then actual revenue Month to date in values and a corrosponding figure for the budget.
I need to run a select on Mondays to pull data for 7 days prior to the Thursday of last week; i.e. Friday - Thursday inclusive. I'm sure this is simple, but I work with dates so infrequently that I need a refressher.Â
This is how I calculate the ratio of failures in an order:
31 Days Table 1 query sum(CASE WHEN (datediff(dd,serDATE,'2015-01-21')) >= 31 THEN 31 WHEN (datediff(dd,serDATE,'2015-01-21')) < 0 THEN 0 ELSE (datediff(dd,serDATE,'2015-01-21'))END) as 31days1 .
How do i loop and pass dates dynamically in the Datediff?
31 Failures Table 2 query SUM(Case when sometable.FAILUREDATE BETWEEN dateadd(DAY,-31,CONVERT(DATETIME, '2015-01-21 23:59:00.0', 102)) AND CONVERT(DATETIME, '2015-01-21 23:59:00.0', 102)Then 1 Else 0 END) As Failures31,31 Day Cal(Formula) combining both Table 1 and Table 2 ((365*(Convert(decimal (8,1),T2.Failures31)/T1.31day))) [31dayCal]This works fine when done for a specific order.
I want a similar kind of calculation done for day wise and month wise.
2. what approach should I be using to achieve day wise and month wise calculation?
I do also have a table called Calender with the list of dates that i can use.
I have created calcalated measures in a SQL Server 2012 SSAS multi dimensional model by creating empty measures in the cube and use scope statements to fill the calculation.
(so I can use measure security on calculations
as explained here  )
SCOPE [Measures].[C];
THIS = IIF([B]=0,0,[Measures].[A]/[Measures].[B]);
On my SP3 db_name(0) and db_name(1) are returning the same thing. Can anybody else try this? Beta of Yukon is doing the same thing...But the following code returns 1: select db_id(db_name(0))
Run the following: declare @s1 varchar(10), @s2 varchar(10) declare @t table( recordid int identity(1,1)not null,field char(1)not null) insert @t (field) select 'a' union select 'b'select @s1 = '', @s2 = ''select @s1 = @s1 + field +',' from @t order by 1select @s2 = @s2 + field +','from @t order by recordidselect[Weird]=substring(@s1, 1,(datalength(@s1)-1)),[Not]=substring(@s2, 1,(datalength(@s2)-1))
Hi allIn a new installation, if the data directory is stipulated as d:data, itinstalls alldata in d:dataMSSQLdata.I need to place the data in d:mssql7data to incorporate backsup from olddata backuspAny ideas ?CheersRay
At my current workplace, whenever I check table sizes using the'reserved' column from sysindexes, or sp_spaceused, I get a total forall user tables which exceeds the physical size of the database.Running sp_spaceused with no parameteres, I get a NEGATIVE value forunallocated space in the database, but only see this if I return theresults in GRID format in QA (text format gives less output):DatabaseName DatabaseSize Unallocated Spacexxxxx_xxxxx11502.38 MB-4874.80 MBReserved Data index_size unused16602800 KB7013752 KB2381904 KB7207144 KBIf I re-run sp_spaceused with the @updateusage='TRUE' option, thisoutput gets corrected to:DatabaseName DatabaseSize Unallocated Spacexxxxx_xxxxx11502.38 MB2773.76 MBReserved Data index_size unused8770680 KB6928168 KB1808096 KB34416 KBwhich shows a substantial difference in the Reserved/Data/Index/Unusedsizes.This happens every day - any ideas about:1) Why this might be happening on such a large scale, and2) Is it conceivable that these discrepancies in space allocationinformation could be causing performance problems? I can imagine thatif the database is trying to locate free pages on extents yet itsinternal view of these doesn't match reality then this could impededata insertion.Offers anybody?
I've sure I have a problem that hasn't been addressed on the forum exactly. I have a SQL 2000 database that the SSIS designer sees, meaning it is a member of the 'Server Explorer' group. I am trying to update my SQL 2005 database based on values from a SQL 2000 database table using an OLE DB Command data flow transformation. I use a SELECT query in the OLE DB Source control to get the required columns. I use an UPDATE statement to identify where to place the columns retrieved from the source. I get an error that tells me that the update statement fails because it can't identify the SQL 2000 database I am trying to use. The highlighted part of the error is something I haven't seen in the similar posts I've read. And, it's ironic because the server is actually 'linked'.
Error 1 Validation error. Import Moving Averages and Open Interest Data: OLE DB Command [3411]: An OLE DB error has occurred. Error code: 0x80040E14. An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "Statement(s) could not be prepared.". An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "Could not find server 'SIR-Research' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.". Prices_MA_OI.dtsx 0 0
Here is the SELECT statement: SELECT Equity_Moving_Averages.m_d_y, Equity_Moving_Averages.Ticker_symbol, Equity_Moving_Averages.MA_10, Equity_Moving_Averages.MA_20, Equity_Moving_Averages.MA_30, Equity_Moving_Averages.MA_40, Equity_Moving_Averages.MA_50, Equity_Moving_Averages.MA_80, Equity_Moving_Averages.MA_100, Equity_Moving_Averages.MA_160, Equity_Moving_Averages.MA_200, OI_Data.OI_Call, OI_Data.OI_Call_Pricewgt, OI_Data.OI_Put, OI_Data.OI_Put_Pricewgt, OI_Data.PCRatio, OI_Data.pcratio_pricewgt, OI_Data.PctRank365, OI_Data.PC_Diff FROM Equity_Moving_Averages INNER JOIN OI_Data ON Equity_Moving_Averages.m_d_y = OI_Data.m_d_y AND Equity_Moving_Averages.Ticker_symbol = OI_Data.Ticker_Symbol --
I have been trying to use the Clustering algorithm for Anomaly Detection, but it has been quite difficult to get correct results for PredictCaseLikelihood. Using a very large number of clusters helped, but there are other problems. The algorithm does not take into account all the columns in my nested table, but only uses Exists/Not Exists for the nested table key column. In my case the nested table contains also a column with a count of key attribute.
I am about to abandon the Sql Data Mining.
Does anyone have more insights into tuning the Clustering algorithm for anomaly detection?