Calculate Median Of Difference In Days Between Records

Jan 24, 2006

I have a table of sample data

Samples(sample_no, sample_date..)

I have no idea how to do the following in sql server or if its even possible:

1. Calculate the difference in days between all samples.
2. Select the median result

Any trick to get this done would be really helpful

thanks,

DB

View 3 Replies


ADVERTISEMENT

Calculate Median Of Difference In Days Between Records

Jan 24, 2006

I have a table of sample data

Samples(sample_no, sample_date..)

I have no idea how to do the following in sql server or if its even possible:

1. Calculate the difference in days between all samples.
2. Select the median result

Any trick to get this done would be really helpful

thanks,

DB

View 10 Replies View Related

How To Calculate Difference Between Getdate And T1 How Many Days

Oct 10, 2013

i have a table

a1
-----
id t1

How can I calculate the difference between getdate() and t1 how many days.

View 3 Replies View Related

How To Calculate A Date Difference In Days

Apr 2, 2007

Suppose I have these two days fields
ddold 1/1/2005 12:00:00 AM
ddnew 2/1/2007 12:00:00 AM

How can i get the DateDifference of these two dates in days.

View 4 Replies View Related

SQL Server 2014 :: Calculate Running Difference In Values Between Days?

Oct 13, 2015

I am trying to write a query to calculate the running difference between data on different dates. Below is what my table of data looks like. Basically I want to calculate the difference between the total_completed for each state and date.

DateStatesTotal_Completed
08/27/15CA 19,952
09/11/15CA 26,336
10/02/15CA 35,444
10/08/15CA 38,278
08/27/15CO2797
09/11/15CO3264
10/02/15CO4270
10/08/15CO4297

below is what I am trying to achieve:

DateStatesTotal_CompletedCompleted_Difference
08/27/15CA 19,952 0
09/11/15CA 26,336 6,384
10/02/15CA 35,444 9,108
10/08/15CA 38,278 2,834
08/27/15CO27970
09/11/15CO3264467
10/02/15CO42701,006
10/08/15CO429727

below is my code (I almost have what I need) I just can't figure out how show 0 as the completed_difference for the first Date for each state since there is no prior date to calculate against.

MRR_TOTALS_WEEK_OVER_WEEK AS
(
SELECT
T1.[Date]
,T1.States
,T2.Total_Completed
,ROW_NUMBER() OVER(PARTITION BY T1.States ORDER BY T1.States,T1.[Date]) AS ORDERING
FROM TOTAL_CHARTS T1
LEFT JOIN TOTAL_COMPLETED T2 ON T1.[Date] = T2.[Date] AND T1.States = T2.States
)

[code].....

View 4 Replies View Related

Calculate Difference Between Two Records?

Aug 28, 2015

I have table that contains below data

  CreatedDate               ID             Message
  2015-05-29 7:00:00      AOOze            abc
  2015-05-29 7:05:00      AOOze            start

  2015-05-29 7:10:00      AOOze            pqy
  2015-05-29 7:15:00      AOOze            lab
  2015-05-29 7:20:00      AOOze            lmn   

  2015-05-29 7:30:00      AOOze            start
  2015-05-29 7:35:00      AOOze            stop

  2015-05-29 7:40:00      AOOze            pqy
  2015-05-29 7:45:00      AOOze            stop
  2015-05-29 7:50:00      AOOze            lmn   

I need to Find Maximum interval time for between message like Start and Stop as per order of createdDate.

For example:

OccuranceCount       MinDate                    MaxDate          DurationInSeconds
1                 2015-05-29 7:05:00      2015-05-29 7:35:00   30
2                 2015-05-29 7:30:00      2015-05-29 7:45:00   15

View 6 Replies View Related

Calculate Median!!!

May 29, 2007

I need to calculate Median on each calculated result from the query below. There is one Median function available in SQL2K but it is not working. Can anyone help me in this regard.

------------------------------------------------------------------------
SELECT INS.Code As [code],INS.FinYr as [YEAR], ' ' As [FIRE BUSINESS], (INSRev.FI_NetPremLessIns / INSRev.FI_GrPremium) * 100 As [Rention Ratio],
(INSRev.FI_NetClaimPaid/INSRev.FI_AdjNetPremium)*100 As [Claim Ratio], ((INSRev.FI_AgencyCommPaid+INSRev.FI_ReInsCommPaid+INSRev.FI_MgmtExpenses+INSRev.FI_OthExpenses)/INSRev.FI_AdjNetPremium)*100 As [Expense Ratio],
((INSRev.FI_NetClaimPaid/INSRev.FI_AdjNetPremium)*100)+(((INSRev.FI_AgencyCommPaid+INSRev.FI_ReInsCommPaid+INSRev.FI_MgmtExpe nses+INSRev.FI_OthExpenses)/INSRev.FI_AdjNetPremium)*100) As [Combine Ratio],
(INSRev.FI_ClosingBal/INSRev.FI_NetClaimPaid) As [Unexpired Risk Reserve to Net Claim(x)],(INSRev.FI_MgmtExpenses/INSRev.FI_AdjNetPremium)*100 As [Management Expenses to Adj. Net Premium],
(INSRev.FI_AgencyCommPaid/INSRev.FI_AdjNetPremium)*100 As [Agency Commissioned to Adj. Net Premium]

FROM
(InsuranceGen As INS LEFT JOIN INSURANCEGen As INS1 ON (INS1.FinYr=INS.FinYr-1 AND INS.Code=INS1.Code))
LEFT JOIN INSRevGen as INSRev ON (INS.Code=INSRev.Code AND INS.FinYr=INSRev.FinYr) WHERE INS.Code IN ('ABC1','ABC2','ABC3') AND INS.FinYr=2005 ORDER BY INS.Code, INS.FinYr
----------------------------------------------------------------------

Thanks

View 5 Replies View Related

Calculate Median LTM

Apr 22, 2008

Using SQL Server 2005, I have the following query to calculate the median sales of each quarter over the past 5 years:


WITH CompMedian AS

(

SELECT SoldDate, SoldPrice, ROW_NUMBER() OVER(PARTITION BY Convert(Varchar(5),Year(SoldDate)) + Convert(Varchar(5), RIGHT(CAST(100+DATEPART(QQ,SoldDate) AS CHAR(3)), 2)) ORDER BY SoldPrice) AS RowNum, COUNT(*) OVER(PARTITION BY Convert(Varchar(5),Year(SoldDate)) + Convert(Varchar(5), RIGHT(CAST(100+DATEPART(QQ,SoldDate) AS CHAR(3)), 2))) AS Cnt FROM tbl_Orders
WHERE Status = 'Sold'

AND SoldDate >= DATEADD(Year, -5, Convert(DateTime, Convert(Varchar(5),Month(GetDate())) + Convert(Varchar(5), '/1/') + Convert(Varchar(5), YEAR(GetDate()))))

AND SoldDate < DATEADD(Year, 0, Convert(DateTime, Convert(Varchar(5),Month(GetDate())) + Convert(Varchar(5), '/1/') + Convert(Varchar(5), YEAR(GetDate()))))
)

SELECT Convert(Varchar(5),Year(SoldDate)) + Convert(Varchar(5), RIGHT(CAST(100+DATEPART(QQ,SoldDate) AS CHAR(3)), 2)) AS CompDate, AVG(SoldPrice) AS CompMedian

FROM CompMedian

WHERE RowNum IN((Cnt + 1) / 2, (Cnt + 2) / 2)

GROUP BY Convert(Varchar(5),Year(SoldDate)) + Convert(Varchar(5), RIGHT(CAST(100+DATEPART(QQ,SoldDate) AS CHAR(3)), 2))

ORDER BY CompDate;


Now my client would like me to change the query so that each quarter would represent the median for the past 12 months ending with that quarter. I've been looking at this for hours and I'm at a loss. Anyone have any thoughts?

Thanks in advance,
Russ

View 2 Replies View Related

Calculate Median Value

Dec 15, 2005

I am converting a report created using Crystal Reports 10 to Reporting Services.  The report contains a list of items with dollar values.  The original report displays both the Average and Median value.  I can easily ( using avg(Field1.Value!) ) determine the average but cannot find a function to determine the median.

How can I add the Median to the report?

 

Thanks in advance,

Greg

View 21 Replies View Related

Using Report Builder 3.0 To Calculate Median?

Sep 14, 2015

I'm using custom code in an expression to calculate the median of a column. It works fine up to a point. Like if there are 35 rows in the result set (or up to some number) but when it gets bigger results, like 42 rows or more it doesn't work, the median is -1. This is the custom code I'm using (found online).

I don't see anything limiting the count, but it comes back with a -1 median so I think that means the count is not > 0.

I have a column in the report called arrival_to_complete which is like: 53 min

I create a column with expression: =MAX(Code.AddValue(Val(Fields!Arrival_to_complete.Value))) to fill the array using just the number part of the column. Then in the report I have 'Median =' <expression>, where the expression is: =Code.GetMedian() I run the report with 2 parameters a begin date and an end date. I don't see where any of this should be limiting the median calculation so I don't get why it works sometimes and not other times.

Dim values As New System.Collections.ArrayList
Function AddValue(newValue As Decimal)
If values is Nothing Then
values = New System.Collections.ArrayList
End If
values.Add(newValue)

[code]....

View 0 Replies View Related

Remove Weekends And Non Working Days When Calculating Days Difference Between Two Dates

Jan 7, 2014

I have an SQL code below which removes weekends and non working days when calculating days difference between two dates:

ce.enquiry_time represents when the enquiry was logged

(DATEDIFF(dd, ce.enquiry_time, getdate()) + 1)
-(DATEDIFF(wk, ce.enquiry_time, getdate()) * 2)
-(CASE WHEN DATENAME(dw, ce.enquiry_time) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, getdate()) = 'Saturday' THEN 1 ELSE 0 END)
-(SELECT COUNT(*) FROM nonworking_day WHERE nonworking_day.nonworking_date >= ce.enquiry_time AND nonworking_day.nonworking_date < dateadd(dd,datediff(dd,0,getdate()),1))

It works but I don't understand how it works it out. I am having issues understanding each coloured piece of code and how it works together.

View 1 Replies View Related

SQL Server - Select Records Added Today, Last 3 Days, 7 Days...

Oct 25, 2006

Hello,I am writing a query to select records added to a table today, in the last 3 days, in the last 7 days, and so on.Here is what I have (which seems that its not working exactly).   -- total listed today
SELECT COUNT (*) FROM mytable WHERE DATEDIFF(Day, mydatecolumn, getdate() ) <= 0-- total listed yesterday
SELECT COUNT (*) FROM mytable WHERE DATEDIFF(Day, mydatecolumn, getdate() ) <= 1-- total listed in the last 3 days
SELECT COUNT (*) FROM mytable WHERE DATEDIFF(Day, mydatecolumn, getdate() ) <= 3I'd like to be able to select the count for records added within the last X number of days. Can someone please help me out?  Thanks so much in advance.

View 1 Replies View Related

Calculate No Of Days

Apr 25, 2008

Hi,
I want to get the no of saturdays that are coming between given span of days,

ex:- if i give dates as 04/05/08 and 04/25/08 , i want to get the no of saturdays between these dates

can anyone help

View 3 Replies View Related

How Can I Calculate The Days Past Due

Apr 20, 2008

If I have and invoice date column and I want to now what invoices are 15 days past due or 30 days past due, how do I do this in a where clause?
WHERE tblInvoices.InvoiceDate ???

View 1 Replies View Related

Calculate Number Of Days

Aug 28, 2004

I need to add days to a date field, my date field is as varchar(20041030 for example) and I need to add 4 days to it, my result should be 20041103, result field is also in varchar,how would I do that, can anyone pls help?

thx in advance!!

View 2 Replies View Related

Query To Calculate Network Days

Apr 15, 2010

I have a requirement where i need to calculate the age of a work order excluding the Weekends (Sat,Sun) in an SQL table, this i need to updated as a formula for a particulay column in the SQl table so when a task startdate is enterred and submitted the Age field gets populated with the number of working days.

Example:
startdate = '04/09/2010'
currentdate = '04/12/2010'
the result should show 1 day and not 3 days.

View 20 Replies View Related

How To Calculate Average Number Of Days Taken

Jan 16, 2014

How to calculate the overall average number of days taken to complete something.

The two fields are enquiry_date (date enquiry is recorded) and complete_date (date enquiry completed/closed).

Each enquiry has a enquiry_number

Sample data typically looks like:

Enquiry number - enquiry_time - complete date
1 - 01/01/2014 - 12/01/2014
2 - 01/01/2014 - 11/01/2014
3 - 01/01/2014 - 10/01/2014
4 - 01/01/2014 - 07/01/2014
5 - 01/01/2014 - 12/01/2014
6 - 01/01/2014 - 04/01/2014

etc.

What is the piece of SQL which looks at the average date difference for each enquiry and then sums it all up to give an overall average number of days it takes?

View 2 Replies View Related

Calculate The SUM For 1 Month & 5 Days -display

Dec 18, 2007

Hi All,

I am new to SQL programming, i have only a fair knowledge on sql programmin.So, I apologies for any silly questions-

I have a Table1 which contains
C1-acountid
C2-date
C3-grossamount(postivie and negative decimal values)
C4-netamount

Table2
C1-groupid
C2-accountid

Table 3
C1-groupid
C2-groupname


I need create a store procedure to retrieve the following on a single table

1. top 10 losers of the day i.e. 10 AccountIDs with the greatest negative Grossamount for the day
NOTE:These 10 AccountIDs may be sam or differing each day
2.sum of Netamount for each AccountIDs listed in STEP 1 since the beginning of the month.
NOTE:These 10 AccountIDs may be same or differing each day and each day sum of netamount should be from beginning of the month till current date.
3.Sum of Netamount for the last 5 days for each accountids in STEP1


The result set must contain the columns as below

C1-accountid
C2-date
C3-net loss for 10 losers on the current date since the beginning of the month
C4-Sum of Net for last 5 days
C5-groupname


Please help me.

Below is the script that i have written, without calculating the sum

(
select top 10 a.date, a.accountid, a.gross, a.net, c.groupname
from GBSys_Sum_EOD a

join server2.dbname.dbo.table2 b on a.accontid=b.accounit=id
join server2.dbname.dbo.Table3 c on b.groupid=c.groupid

where date> getdate()-1
and gross< (floor(-00.00)) order by gross
)

Thanks in advance.

View 2 Replies View Related

SQL 2012 :: Calculate (Number Of Days To Pay) Logic

Jun 24, 2014

How to write a query that calculate the number of days (approx) that it takes to a customer to pay an invoice.

Document Types

1 Payment
2 Invoice
3 Credit Memo
4 Finance Charge Memo
5 Reminder
6 Refund

There are three methods to consider when calculating the days to pay logic.

Method 1 - Simple : Look for Document Type 2 (Invoice), if "closed at date" > "posting date" then number of days = ("closed at date" - "posting date")

Method 2 - A Document Type 1 (payment) closes a Document Type 2 (Invoice)
For this method the formula would be: Payment Record (1) "posting date" - Invoice Record (2) "posting date"

Method 3 - An Invoice closes the payment.

On a payment entry “closed by entry no.” refers to an Invoice entry.

a. In our code we are not on the payment looking for the invoice, we are on the invoice.
i. Because of this we need to find the entry that our current invoiced has closed.

I am taking this from a page that has the pascal code that I need to translate to SQL.

IF (CustLedgEntry2."Document Type" = CustLedgEntry2."Document Type"::Invoice) AND
NOT CustLedgEntry2.Open
THEN
IF CustLedgEntry2."Closed at Date" > CustLedgEntry2."Posting Date" THEN
UpdateDaysToPay(CustLedgEntry2."Closed at Date" - CustLedgEntry2."Posting Date")

[Code] ....

I am also including create table and insert data scripts ...

View 9 Replies View Related

SQL Server 2008 :: Calculate Number Of Days

Oct 8, 2015

I have client table which has client_id Eff_from and Eff_to columns.Eff_from and Eff_to are the dates that client is eligible for service. I need to know the average number of days from the day that he became not eligible and new eligibility date .

CLIENT_IDEFF_FREFF_TO
1001 12/24/200712/8/2010
100112/13/20123/26/2013
1001 5/27/20138/2/2013
10019/24/201310/30/2016

for expl days between
12/8/2010 and 12/13/2012
3/26/2013 and 5/27/2013
8/2/2013 and 9/24/2013

then AVG them.

View 3 Replies View Related

Calculate Total Working Hours Between Days

Nov 15, 2013

I have to calculate the total working hours between days, there hours must get automatically round off to nearest value example:

Date :12-05-2013 time : 4:15 will change to 4.00 and if Date :13-05-2013 time: 4:25 then needs to 4.30 and sum the above total hours and results Total : 8.30 hrs.

View 3 Replies View Related

Calculate Contract Days In Financial Year

Feb 4, 2015

I have a table with 3 fields: Contract_No, Start_Date, End_Date. I need to calculate how many of the days between the Start and End dates fall within each financial year (FY) beginning 1st April and ending 31st March.

So for example if the Contract Start_Date is 26/01/2012 and the End_Date is 20/05/2012 or is null then the number of days for 2012 FY is 49 (counting from 01/04/2012 to 20/05/2012).

If the End_Date is null for the same contract, then the number of days for 2012 FY would be 365.

Since the contract period from Start_Date to End_Date might span more than one or even several FY I need to be able to show this in columns seperately for each FY. What is the best way of achieving this?

View 6 Replies View Related

Calculate Difference?

Dec 30, 2003

I am having trouble creating a sp for the following situation:

The database contains a record of the mileage of trucks in the fleet. At the end of every month, a snapshot is collected of the odometer. The data looks like this:


Truck Period Reading
1 1/31/03 55102
2 1/31/03 22852
1 2/28/03 62148
2 2/28/03 32108
1 3/31/03 69806
2 3/31/03 52763

How can I calculate the actually miles traveled during the month in a query?

TIA,

Rob

View 7 Replies View Related

Difference Between Days Of The Week

Aug 15, 2006

Hi! I am totally new to the forum and to the SQL.

Need your advice. My report will run on Friday automatically and I need to retrieve the data from previous Friday until Today’s Friday.

I have an example from another developer’s code, but this one gets the data on the previous day. Can you please help me to right the expression?

Here is an example ‘on the previous day’

CAST(CONVERT(CHAR(10), tbl1.closeddate,120) as datetime) = CAST(CONVERT(CHAR(10), dateadd(day, -1,getdate()), 120) as datetime)

This is what I did (assuming today is Friday)

(tbl1.closedDate BETWEEN CAST(CONVERT(CHAR(10), DATEADD(day, - 8, GETDATE()), 120) AS datetime) AND CAST(CONVERT(CHAR(10),
DATEADD(day, - 1, GETDATE()), 120) AS datetime))

I don't get any records back.

Please help.
Thanks a lot.

View 11 Replies View Related

How To Calculate The Total Days Between Open And Close Date

Apr 6, 2006

Hi All,
I have a table call case and case_status have two fields, date and status as below:
date                          status
04/01/2006               open
04/05/2006               closed
04/10/2006               open
04/15/2006               closed
Whenever i open and closed the case, one record is insert into the case_status table.
Now I would need to calculate the total days of the case in storeprocedure.
Anyone can help me please.
Aung

View 5 Replies View Related

DATEDIFF Case Statement - Calculate Number Of Days

Feb 14, 2014

Aim – Calculate the number of days between the [CreatedDate] and getdate, however if stage name = ‘Live Transactions’ then Calculate the number of days between [CreatedDate] & [CloseDate]

This is my query so far

SELECT [CreatedDate]
,[StageName]
,[CloseDate]
,DATEDIFF(dd,CONVERT(datetime,[CreatedDate]),GETDATE()) as Age
FROM [FDMS].[Dan].[Raz_Reporting_LCS]

Which produces the following

CreatedDate2012-12-17
StageNameLive Transactions
CloseDate2012-12-31
Age424

When in fact the age should be 14days

View 7 Replies View Related

Transact SQL :: Calculate Working Days Excluding Weekends

Jun 7, 2015

Iam trying to calculate the number of working days between two dates. Iam getting the uouput as only 1 02 r working days??

select  building_number as SchoolID,building_name as Campus,   count( distinct( CASE  WHEN(( DATEPART(dw, CurDate) + @@DATEFIRST)%7 NOT IN (0,1)) tHEN 1 ELSE 0 END)) as NumberofDaysServed   from   Sales sl join Buildings b on  sl.Building_Num =b.Building_number join students2 s on  s.Student_Number= sl.Student_Num   join Sale_Items SI on   si.UID = sl.UID   where  CONVERT(CHAR(10),CurDate,120) between '2015-05-01' and   '2015-05-07'      and VoidReview <> 'v' and  SI.INum = '1'    group by  building_number,building_name order by building_number,Building_Name;

View 8 Replies View Related

Calculate Number Of Working Days Back From A Date

May 6, 2008

Hi,
I need to calculate the number of working days from a date backwards. For example 2 working days before Thursday would be the Tuesday (as a basic example)

I use the following code and a Calendar table to calculate the working days from a date but can anyone help with reworking this query to do the reverse

declare @WorkingDate as datetime

SELECT @WorkingDate=dt
FROM tblCalendar AS c
WHERE (@WorkingDays =
(SELECT COUNT(*) AS Expr1
FROM tblCalendar AS c2
WHERE (dt >= @StartDate) AND (dt <= c.dt) AND (IsWeekday = 1) AND (IsHoliday = 0))) AND (IsWeekday = 1)
AND (IsHoliday = 0)

-- Return the result of the function
RETURN convert(varchar(12),@WorkingDate,106)

Hope someone can help

Thanks

View 3 Replies View Related

Calculate Difference Between Two Dates

Oct 18, 2006

Hi, i'm trying to calculate the number of days between two dates, but within an UPDATE statement, so far I can't wrap my head around how I can update a field with the number of days.

I was thinking something like


Code:

Update #ClaimMaster
Set covered_days = (then insert select statement that subtracts the two dates)



Does that make any sense?

View 1 Replies View Related

Calculate Difference Between Two Rows

May 15, 2006

Hi,

i have a matrix, and in that matrix i need to have one column which calculates the percentage change between a value on the current row and the same value on the previous row.

Is this possible? The RunningValue() function isn't of help as it can't help me calculate the change between two rows, and Previous() doesn't work in a matrix (why???!!!!!). Also calculating this as part of the query isn't possible as there is a single row group on the matrix, and the query is MDX.*

Thanks,

sluggy

*for those who are curious, the matrix is showing data an a per week basis, the row group is snapshot date, i am trying to measure the change in sales at each snapshot.

View 8 Replies View Related

Need Sql To Calculate Percentage Of Difference

Oct 23, 2007



so I have some data that looks like this:
semester weekOfSemester counts
Fall 2006 4 1
Fall 2007 4 6



I want to eventually graphically represent this data over the 18 weeks of the semester in terms of Fall 2007. I need to show change weather positive or negative as a percentage against Fall 2006. Can someone help with the sql?


thanks

kam

View 3 Replies View Related

T-SQL (SS2K8) :: Calculate 90 Days And 3 Years Ago From Effective Date In A Table?

Sep 30, 2014

What would be the most straight forword to Calculate 90 days and 3 Years ago from an Effective Date in a table?

as in

SELECT EffectiveDate
from FL.CEFHistory

I need to return the effective date - 90 days and 1 year from that.

[URL]

View 6 Replies View Related

Power Pivot :: Calculate Number Of Business Days Between Two Dates

May 14, 2015

I am looking for a formula to calculate the number of weekdays/business days between two dates in power pivot.I do the same in SQl using  the following query

    DATEDIFF(dd, Date1, GETDATE()) - (DATEDIFF(wk, Date1, GETDATE()) * 2) -
    CASE WHEN DATEPART(dw, Date1) = 1 THEN 1 ELSE 0 END +
    CASE WHEN DATEPART(dw, GETDATE()) = 1 THEN 1 ELSE 0 END END 

I am looking for a similar query in Power Pivot.

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved