HI,
getdate() gives me today's date. I have a sql query which returns me a date. I want to see if the difference between today's date and the date returned by sql query is 12 months(1 year) or less. If yes I want to print it.
(If the difference is more than 12 months or 1 year i don't want to consider that record.)
Example:
how to do calculate:
10/05/2004-10/3/2003
Hello, I have a problem I wish to share and get help if possible. I am trying to create a database function that will calculate working hours lost between two dates for every employee, however, I am new to database functions and I cannot find information on how to solve my rather "unique" problem. The dates for calculations are based on employee absences for a given period of time. The tables I have and fields of interest are as follows: I have two tables T.Abs and T.Job where T.Abs contains absence records while T.Job contains job records. The tables are in a star schema with T.Job being the main fact table. the tables have the following fields (keys are underlined) T.Abs T.Job EMPLID EMPLID EMP_RCD EMP_RCD EFFSEQ EFFSEQ EFFDT EFFDT ABS_START (7 other columns as follows) MON_HRS, TUE_HRS, WED_HRS .....up to....... SUN_HRS ABS_END
Each time a report is generated for an absence, two prompts come up to define the report period. @prompt(begin_date) and @prompt(end_date) The actual period to calculate hours lost is determined as follows:
Report start period If ABS_START BETWEEN @prompt(begin_date) AND @prompt(end_date) THEN ABS_START ElseIf ABS_START < @prompt(begin_date) AND ABS_END BETWEEN @prompt(begin_date) AND @prompt(end_date) THEN @prompt(begin_date) ElseIf ABS_START < @prompt(begin_date) AND ABS_END > @prompt(end_date) THEN (If ABS_START < @prompt(begin_date) THEN @prompt(begin_date) ELSE END If) ELSE END If
Report End period If ABS_END BETWEEN @prompt(begin_date) AND @prompt(end_date) THEN ABS_END ElseIf ABS_END > @prompt(end_date) AND ABS_START BETWEEN @prompt(begin_date) AND @prompt(end_date) THEN @prompt(end_date) ElseIf ABS_START < @prompt(begin_date) AND ABS_END > @prompt(end_date) THEN ( If ABS_END > @prompt(end_date) THEN @prompt(end_date) ELSE END If) ELSE END If
Given the above parameters, T.Job.EFFDT can fall outside the desired range but the calculation for the working Hours lost should not be affected by this. I am new to SQL in general therefore suggestive code would be more than welcome.
Another thing to bear in mind, I am dealing with a transactional database therefore I have to use max(T.Job.EFFDT) to avoid any duplications and max(T.Job.EFFSEQ) for the same reasons.
I have a tricky question to Microsoft SQL Server 2000/2005. I have failed to find a solution to the problem yet and others have failed too. So I thought that I throw it around here, because the fact that a lot of knowledgeable DBAs hang around in this forum.
I am looking for a script/stored procedure that is able to show me upcoming job executions for a selected date/time range based on the current settings for the jobs configured on the Database server.
Example Date/Time From: 2/16/2007 00:00 a.m. (Friday) Date/Time To: 2/17/2007 12:00 p.m. (Saturday)
A. Job 1 / Schedule 1 = Week Days, 1:00 a.m. B. Job 1 / Schedule 2 = Saturdays, 10:00 a.m. C. Job 2 / Schedule 1 = hourly, between 10:00 a.m. and 1:00 p.m. D. Job 3 / Schedule 1 = every 3rd Saturday of the month, 5:00 a.m. E. Job 4 / Schedule 1 = every 1st Friday of the month, 8:00 a.m.
The routine I have in mind would not return Job E, because 2/16/2007 is the 3rd Friday of the month and not the first.
It needs to return the Job ID, the Job Name, the Schedule ID, the Date and the Time. Disabled Jobs and Schedules are by default excluded from the selection, but an option to include or exclude those would be a bonus. Information such as the min, max and average execution time would be great too.
Notes
The schedules of Job D and Job B overlap as you can see in my example above. This happens only once per month though. I have over 20 jobs with sometimes very frequent execution times, like every 5 minutes or every 20 minutes and jobs that run hourly, daily, weekdays only, weekends only, monthly once etc.
Purpose
I want to do two things. I want to determine where jobs overlap, not just by start date/time, but also by average run time and maximum run time.
I also want to be able to generate a report that shows me what should have been done and what was actually done by the jobs (note on the site, 6 of the jobs create new jobs on the fly for other database servers and this is sometimes not happening properly, without getting any error message. The volume of jobs makes the manual search like a search for a needle in a haystack.)
Findings so far:
I did some digging myself and found following stored procedures that do some of the steps that I need and involved tables for the calculation.
Stored procedures: - sp_get_schedule_description (in db: msdb) (undocumented stored procedure) - sp_add_schedule (in db: msdb) http://msdn2.microsoft.com/en-us/library/ms187320.aspx
It is not a problem to determine the next execution of a job, but that is not what I need, anyway. The problem is that it does not help you to determine all upcoming execution times, if the selected timeframe is long enough that SQL Server executes the job more than once.
There is no way around using the sysjobschedules table and calculate the execution dates and times based on the configured settings. See the Stored procedure: sp_get_schedule_description.
That one breaks down nicely the settings as documented for sp_add_schedule at http://msdn2.microsoft.com/en-us/library/ms187320.aspx, but it does not allow the determination of the exact upcoming dates and times when the job is supposed to be executed.
Another Example If there is only one job scheduled to run
1) every 5 minutes, 2) on every weekday 3) between 1:30pm and 2:00pm
You would get the following results
1) start date/time 7/7/2007 12:00pm, end date/time 7/8/2007 2:00pm
nothing, because the 7/7/2007 and 7/8/2007 are on the weekend
2) start date/time 7/5/2007 12:00pm, end date/time 7/5/2007 1:45pm
Now SQL has a lot more configuration options for the scheduler.
And don't forget that you can have more than one schedule record for any single job, including no-schedule record (which would not interest me).
Autom. when SQL starts freq_type=64 Starts when CPU idle freq_type=128
One Time On Date mm/dd/yyyy at time: hh:mm:ss am/pmfreq_type=1 or Recurring
Occurs Daily freq_type=4 Every x day(s)freq_interval=x Weekly freq_type=8 Every x week(s) onfreq_recurrence_factor=x
Mo [ ], Tu [ ], We [ ], Th [ ], Fr [ ], Sa [ ], Su [ ],
1 = Sunday, 2 = Monday, 4 = Tuesday, 8 = Wednesday, 16 = Thursday, 32 = Friday, 64 = Saturday. Examples: Su and Mo enabled = 3 (1 (Su) + 2 (Mo)), Mo, We and Fr enabled = 42 (2 (Mo) + 8 (We) + 32 (Fr)) Monthly freq_type=16 Day X of every Y month(s)freq_interval=X freq_recurrence_factor=Y or
The 1st,2nd,3rd,4th,LAST WEEKDAYfreq_type=32 of every Y month(s)
freq_relative_interval=1,2,4 (3rd),8 (4th),16(last) freq_interval= 1=Su,2=Mo,3=Tu,4=We,5=Th,6=Fr,7=Sa,8=Day,9=Weekday,10=Weekend day freq_recurrence_factor=Y
Occurs Once at hh:mm:ss AM/PMfreq_subday_type=0x1 or occurs Every X Hours/Minutes Starting: hh:mm:ss A/PM freq_subday_type=0x4 (minutes) or 0x8 (hours) Ending: hh:mm:ss A/PMfreq_subday_interval=X active_start_time active_end_time
Start Date mm/dd/yyy End Date mm/dd/yyyyactive_start_date oractive_end_date No End Dateactive_end_date=99991231
Does anybody has a script that does that or several individual scripts that would have to be combined to do what I want to do?
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]);
How can I do this with Parameters? I can get a single parameter to filter for a single date (or even a combo list of the dates in DB). But I want my parameters to interact so that they specify a range. Is this possible?
Today I have got one scenario to calculate the (sum of days difference minus(-) the dates if the same date is appearing both in assgn_dtm and complet_dtm)/* Here goes the table schema and sample data */
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[temp_tbl]') AND type in (N'U')) DROP TABLE [dbo].[temp_tbl] GO CREATE TABLE [dbo].[temp_tbl]( [tbl_id] [bigint] NULL, [cs_id] [int] NOT NULL, [USERID] [int] NOT NULL,
I have a table that has hotel guests and their start stay date and end stay date, i would like to insert into a new table the original information + add all days in between.
I want to know if there is a way to compare dates in the sql statement with dates that I input into a database and todays date. the datatype that I'm using is smalldatetime.The statement I used is:Select Date from Table where Date > 'Today.now'I get an errorCould this be done or is there another approach?
I have a table which records employees'time-off records. There are 6 columns in this TimeOff table. They are RequestID, EmpName, StartDate, EndDate, Type, NumofDays. I have another table which has all the dates from 01/01/1950 to 01/01/2056.
I am trying write a query which lists all the dates between the timeoff startdate and enddate, including the the start and end dates, but my query so far only lists the start and end date in a timeoff record:
SELECT D.[Date], Datename(dw,D.[Date]) AS Weekday FROM Dates D LEFT JOIN TimeOff T ON D.[Date] = T.OffStartDate OR D.[Date] = T.OffEndDate WHERE (OffType = 'Sick Day' AND EmpName = 'Cat White') AND (D.[Date] BETWEEN T.StartDate AND T.EndDate)
Has anyone ever written a function to retrieve all individual dates between two given dates? Using DATEDIFF I can get the number of days between two dates. However I need to iterate through the days to identify weekend and holiday dates. Has anyone ever written a function to do this?
So, if select datediff(d,'07/01/2007','07/15/2007') as NumOfDays returns 14, I'd need to iterate through the 14 days and get the weekends and holidays. Would I have to use a cursor to iterate through the days?
My predicament is - where do I do these calculations - in my vb.net code or in an SQL stored procedure?
My manager has handed me a task of converting an excel file she uses in to a web aplication.
While it has been easy to devise what should be the screens and how to capture data, I am struggling over how to code the calculations.
The calculations in excel are pretty simple. These are just sequential calculations (about a 150 calculation for average 500 rows). Mathametical operations include sum, average, max min - regular excel stuff. Some calculations involve vlookup (equvalent to calculation based on value derived from a reference table).
So I am stil wondering - where do I do these calculations - in my vb.net code or in an SQL stored procedure?
Since these calculations are required a produce a result in an online environment, what will be faster?
I tried to do a proof of concept by creating a sample calculation in a .NET class and an in a stored procedure. The choice is still not clear. SQL code execution time was not bad. But SQL code tended to be very messy.VB.net code seemed to be a little slow. But seemed a more organised to look at.
Any views that you can offer will be very helpful.
I need to calculate the overall GPA for a student in a particular class.
YEAR SCHOOL STUDENT IDENT GRADE TEACHER CLASS GPA 2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 0.0000 2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 1.6700 2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 3.3300 2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 3.6700 2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 0.0000 2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 0.6700 2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 1.0000
The problem I'm having is that a student may not taken the class for four terms (as in the Elementary Algebra example above). So I can't hard code it to sum the gpa and divide by 4; it needs to be the number of terms the student took the class.
Here's my sql:
select trnscrpt.schyear as [Year], school.schname as School, rtrim(stugrp_active.lastname) + ', ' + rtrim(stugrp_active.firstname) as Student, trnscrpt.suniq as suniq, stugrp_active.graden as Grade, trnscrpt.teachname as Teacher, trnscrpt.descript as Class, gpamarks.gpavallvl0 AS GPA
from dbo.trnscrpt inner join dbo.stugrp_active on trnscrpt.suniq = stugrp_active.suniq INNER JOIN school ON stugrp_active.schoolc = school.schoolc INNER JOIN gpamarks ON trnscrpt.marksetc1 = gpamarks.marksetc AND trnscrpt.markawd1 = gpamarks.mark
where trnscrpt.graden >= 6 and trnscrpt.markawd1 not in ('NC','NG','P','W','WA','WF','WI','WP') and trnscrpt.subjectc in ('LA', 'MA', 'CP', 'CB') and trnscrpt.schyear = 2007 and stugrp_active.schoolc = 725
In period = 2, status code change from InStock to OutOfStock: Product 1 (Count=1) In period = 1, number of products with status code = InStock: product 1 and product 2 (Count=2)
sector RefDate price pharm 22 august 2007 100.21 gap 15 august 2007 10.32 pharm 21 august 2007 99.99 pharm 9 oct 2007 100.99 pharm 2 oct 2007 98.34 pharm 8 oct 2007 96.34 ...
I would like to have the result as follows: sector RefDate price priceChangeSinceYesterday priceChangeSinceLastWeek priceChangeSinceLastMonth pharm 9 oct 2007 100.99 100.99-96.34 100.99-98.34 100.99-lastmonth's price value
select sector, RefDate, price, priceChangeSinceYesterday??, priceChangeSinceLastWeek???, priceChangeSinceLastMonth?? from table1
My aim is to do something like what I have explained below and I was planning on building this logic at the Database level only rather than on the frontend code.
There are certain allocations(transactions) that happen on a periodic basis and I am storing these transactions in the PurchaseTranMaster and PurchaseTranDetail table. These transactions are categorized as 'Main' type and the amount could be allocated for one or many categories in a single transaction. Below is how it will be saved in the 2 table
PurchaseTranMaster
TranID TranDate TranType 1 14-March-2008 Main 2 17-March-2008 Main 3 1 9-March-2008 Main
PurchaseTranDetail
TranID Amount Category Debit_TranId 1 1000 A 1 1000 B 2 2000 B 3 300 A 3 400 C
Now what happens is users of my application can make purchases under all these categories only until the Balance under these categories is > than purchase amount. The Balance is calculated as sum of all transactions. It means that w.r.t the above data the balances for each category is(this is not stored in the database)
A 1300 B 3000 C 400
So lets say a user does make a purchase(Trantype is 'SUB') of 300 under A and 400 under B in a single transaction. The data would then be stored in the tables as
PurchaseTranMaster
TranID TranDate TranType 1 14-March-2008 Main 2 17-March-2008 Main 3 19-March-2008 Main 4 20-March-2008 SUB
PurchaseTranDetail
TranID Amount Category Debit_TranId 1 1000 A 1 1000 B 2 2000 B 3 300 A 3 400 C 4 300 A 1 4 400 B 1
In the PurchaseTranDetail the Debit_TranId value means that the amount has been marked against the TranID 1. This TranId is not handpicked by the user and the system should allocate it accordingly based on the amount available for a particualar category for a Main Transaction. It means that before TranId 4 was saved in the database then the system would first check whether the Total available balance for A >=300 and B>=400 (in our example above it is 1300 and 3000 resp) Then if the Balance is > than the puchase amount then the allocation would be done by the system and this would be done against the TranID whose TranDate was the earliest, so thats why the Debit_TranId column has 1 as TranId 1 was the earliest.so logically now the balance for the categories would be (this is not saved in the database)
A 1000 B 2600 C 400
So next time again when a user would make a purchase(transaction) under A for 800 and under B for 1000 then if the balance is greater than the purchase amount(which in this case it is) the allocation would happen according to the earliest TranId and this time amount would be partly marked against TranId 1 , TranID 2 and TranID 3. The data would look like this
PurchaseTranMaster
TranID TranDate TranType 1 14-March-2008 Main 2 17-March-2008 Main 3 19-March-2008 Main 4 20-March-2008 SUB 5 21-March-2008 SUB
TranID Amount Category Debit_TranId 1 1000 A 1 1000 B 2 2000 B 3 300 A 3 400 C 4 300 A 1 4 400 B 1 5 700 A 1 5 100 A 3 5 600 B 1 5 400 B 2
I need to do the above taking into consideration that there could be multiple users making purchases(concurrency). Also I was building my logic on doing the above whether to use cursors or loops. I just need to know how do I write my stored procedure and what would be the most efficeint way of doing the above.
The design for creating the above sample tables is below
insert into PurchaseTranMaster values(convert(datetime,' 14-March-2008',103),'Main') insert into PurchaseTranMaster values(convert(datetime,' 17-March-2008',103),'Main') insert into PurchaseTranMaster values(convert(datetime,' 19-March-2008',103),'Main') insert into PurchaseTranMaster values(convert(datetime,' 20-March-2008',103),'SUB') insert into PurchaseTranMaster values(convert(datetime,' 21-March-2008',103),'SUB')
insert into PurchaseTranDetail values(1,1000,'A',0) insert into PurchaseTranDetail values(1,1000,'B',0) insert into PurchaseTranDetail values(2,2000,'B',0) insert into PurchaseTranDetail values(3,300,'A',0) insert into PurchaseTranDetail values(3,400,'C',0) insert into PurchaseTranDetail values(4,300,'A',1) insert into PurchaseTranDetail values(4,400,'B',1) insert into PurchaseTranDetail values(5,700,'A',1) insert into PurchaseTranDetail values(5,100,'A',3) insert into PurchaseTranDetail values(5,600,'B',1) insert into PurchaseTranDetail values(5,400,'B',2)*/
I´m working on SSRS 2005 trying to calculate YTD for the total sale. This is what I got so far:
Code Snippet
WITH MEMBER [Measures].[YTD Amount] AS 'SUM(PeriodsToDate([DATE].[Year]),[Amount])' SELECT {[Measures].[Amount],[Measures].[YTD Amount]} ON COLUMNS, [DATE].[Month].Members ON ROWS FROM [SKY] My Date hierarcy is: Year Month
When running this query all I get is very small number for Amount column, almost zero for all months and the YTD Amount Column is only showing (null).
Hello Friends I have 3 tables 1) Product Id, ShortName 2) IncomingStockId, ProductId, Quantity, InDate 3) OutGoingStock Id, OutDate, ProductId, Quantity I need to get the results like thisProduct name, quantity in stock today the "quantity in stock today" = sum (quantity recieved) -sum (quantity sent) Thank you for your timeSara
Hi. i have the code : cmd = New SqlCommand("SELECT sales,country,year FROM salesTable WHERE (country = " & (CountryBlk) & " AND branch = " & (NameSnif) & " AND datepart(yyyy,year)=" & (YearBlk) & ") order by datepart(mm,year) ", cnn) cnn.Open() rdr = cmd.ExecuteReader( _ CommandBehavior.CloseConnection) While x < 12 If rdr.Read = Nothing Then Exit While End If varcount(x) = rdr("sales") TempMonth = rdr("year") MonthNumber(x)=datepart(DateInterval.Month,TempMonth) x = x + 1 End While
i want to calculate and put into the varcount(x) value all sales of the same month
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.
I have scenerio that find out the Bandwitdh size between clint and server. I wanted find out howmuch size of data recieveing from server at a time. Any advice regarding this. Thanks, Ravi
how do i calculate something like this if I have the table with names and count? Name Count Percent Name1 27 4.69% Name2 2 0.35% .... Totals 576 100.00%
I am performing a calculation in both SQL and MSACCESS. ACCESS is correct and SQL is not. It is off by -.05 Here is the calculation:
Sum((ch.FaceAmount)-(((ch.FaceAmount*Ex.CAN_Exchange_Rate+0.005)*100)/100)) AS TransAmount,
Both FaceAmount and CAN_Exchange_Rate are defined as money in a SQL table. The ACCESS front-end attaches this table, so it uses the same columns in the calculation.
Now, I know SQL looks at money with 4 decimal places. The attached SQL tables in ACCESS looks at these columns as currency which I believe is 2 decimal places. I think this is where the descrepency is. But it still doesn't explain why SQL is calculating the incorrect total.
In the following calculation I am receiving my output as 000000.9000. I need it to look like 00000000.90. I cant seem to loose the 2 zeros at the end. Can anyone help me with this? Keep in mind that my output has to be varchar.
right('00000000000' + cast((st.rate_dlr * .01) * 10 as varchar),11)
Hi: I am having a problem with the Syntax. I am trying to get the daily value for a contract_nbr. The selection below shows that I am selecting by Case statement when day = 2 (2nd Day) and the month is a parameter provider by the user. For this particular example, I am using 2 (February). Thanks for the help !!!!
[code] Set @Req_Month = '2'
SELECT Distinct a.contract_nbr, Case when Day(c.Beg_eff_date) = 2 and month(c.Beg_eff_date)= @Req_Month Then c.rcpt_nom_vol-c.rcpt_fuel-rcpt_act_vol Else 0 End As Day_2 from TIES_Gathering.dbo.contract a Inner Join TIES_Gathering.dbo.NOm b on a.contract_nbr = b.contract_nbr Inner Join TIES_Gathering.dbo.Nom_vol_detail c on c.Nom_id = b.Nom_id where (a.contract_sub_type = 'INT') and (a.Contract_type_code ='GTH') and (DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) < a.current_expirtn_date) and (c.rcpt_dlvry_ind ='R') Group by a.contract_nbr [code]
Hello experts! After surfing this forum and reading many articles in the web I still haven't succeeded with a certain calculation that I need to perform. Thus I wanted to address you to ask if you could help me on this one:
I have 3 tables in a SQL Server 2005 DB and want to carry out the following calaculation:
[sum of lmenge/lmenge]* [1/werksmassFM]*p_transpreis
However, whatever I attempt to do, it seems to fail! I am quite a newbe and was never focussed with such comprehensive statements before. I would appreciate any help!
My statement looks like this so far (without the calculation):
SELECT l.bestellnr, l.lfsnr, l.ziel, l.lfs_refnr, l.lfsGuid, CONVERT(NUMERIC(9, 3), l.werksmassFM) AS werksmassFM, ls.lmenge, ls.pguid_ref, p.punktName, p.holzart, CONVERT(NUMERIC(9, 2), p.laenge) AS laenge, CONVERT(NUMERIC(9, 2), p.p_transpreis) AS p_transpreis FROM dbo.lfs AS l INNER JOIN dbo.lfs_sub AS ls ON l.lfsGuid = ls.lfsGuid_ref INNER JOIN dbo.polter AS p ON ls.pguid_ref = p.pguid WHERE (l.lfsnr LIKE '%1253')