Date Differences & CASE

Jun 3, 2008

I have written the SQL below and need to change the case. I need to say that if today’s date (get date) is between <> 4 weeks of sv_latest_appraisal then = Outstanding. Can this be done in SQL? I know it is very specific so not sure. Please help! Sam

SELECT Employee.FORENAME AS Forename,
Employee.SURNAME AS Surname,
Employee.LOCATION AS Location,
Employee.DEPARTMENT AS Department,
Employee.STARTDATE AS Startdate,
Sv_latest_appraisal.NEXT_APP AS Next_app,
Sv_latest_appraisal.USR_EAR_TYPE AS Usr_ear_type,
Sv_latest_appraisal.USR_EAR_TYPE_NEW AS Usr_ear_type_new,
CASE
WHEN Sv_latest_appraisal.NEXT_APP <= getdate() THEN 'OVERDUE'
WHEN Sv_latest_appraisal.NEXT_APP >= getdate() THEN 'NOT DUE'
WHEN Sv_latest_appraisal.NEXT_APP = getdate() THEN 'DUE TODAY'
ELSE 'UNKNOWN'
END
FROM (dbo.EMPLOYEE AS Employee
INNER JOIN dbo.SV_latest_appraisal
ON Employee.EMPLOY_REF = Sv_latest_appraisal.EMPLOY_REF)
INNER JOIN dbo.JOB AS Job
ON Employee.JOB_REF = Job.JOB_REF
WHERE (Employee.LEAVER = 0)AND (Employee.LOCATION LIKE 'GE')

View 20 Replies


ADVERTISEMENT

Query To Return Date Differences

May 23, 2008

Hi Guys,

I hope someone can help, I usually just need to do simple queries, and am fine with that, but this is a bit over my head without a few pointers in the right direction.

I have a table that stores log results from pieces of hardware that contact an internet server periodically.

For simplification, this contains:

LogID
SystemID
DeviceID
ContactDateTime
Notes

Each device contacts the server about once every 5 minutes, and there are about 100 devices in 6 systems.

What I need to do is find out, for a certain date time range, things like:

1. the average time between comunication for any one device
2. the longest time between communication for any one device
3. average time between communications for all devices in a system.

We currently do this by downloading all the logs and working through them programmatically on the server, but as you can imagine, it is a very large amount of information, and it would be much more efficient if this could be done on the SQL server.

Any thoughts on how to achieve this please.

Many thanks

View 2 Replies View Related

Select Case With Date

Aug 2, 2013

OK so I want to use datepart(month,getdate() with a Case statement with this logic:

SELECT CASE
datepart(month,getdate()='8' then
SELECT *
FROM [Master]
WHERE [Month]='Jul'
END

OK what's wrong with the code?

View 6 Replies View Related

Converting Date In Case Statement

Apr 29, 2015

I have a query where I need to see in 2 seperate columns, the Actual date of deliveries and collections, and the Invoice Week number of the same. The problem is that in our ERP system delivery date (di.ddate) is a date field, and the collection date is nvarchar. This is my query and sample results below, as you can see I'm getting nulls for the collection lines. How can I do this efficiently

select di.dticket, di.item,
case di.item when 'DEL' then di.ddate when 'COL' then CONVERT(datetime,di.text2,103) end ActDate,
Case when di.item = 'DEL' then
(select YearWeek from MCSReports.RptRevenueGuideWeekLookup
where di.ddate between FromDate and ToDate) end InvWeek

from deltickitem di
where item in ('DEL','COL')

Sample results below:

dticket item ActDate InvWeek
-------------------- -------------------------------------------------- ----------------------- --------
01-000002 DEL 2011-07-05 15:53:00.000 2011-27
01-000002 COL NULL NULL
01-000004 DEL 2011-07-05 16:04:00.000 2011-27
01-000004 COL NULL NULL
01-000005 DEL 2011-07-05 16:08:00.000 2011-27
01-000005 COL NULL NULL
01-000006 DEL 2011-07-05 16:19:00.000 2011-27
01-000006 COL NULL NULL
01-000007 DEL 2011-07-05 16:24:00.000 2011-27
01-000007 COL NULL NULL
01-000008 DEL 2011-07-05 16:29:00.000 2011-27
01-000021 DEL 2011-07-05 08:48:00.000 2011-27

View 6 Replies View Related

How To Write Date Range On Case Statement

Oct 30, 2012

I have a case statement as follows which I am using in the where clause to get today's data

(Case when (A.ID is null or B.ID = '' or C.ID= ' ') Then convert(varchar,(Case when A.Time is null then B.Time else A.Time end),103)

else convert(varchar,(Case when A.Time is null then ''" else B.Time end),103) end)

=convert(varchar,getDATE(),103)

However I want to know whether I can use a date range on a case statement

I.e. I want to be able to use BETWEEN statement to get a date range

BETWEEN convert(varchar,getDATE(),103) AND convert(varchar,getDATE()-1,103)

How do I achieve this on a CASE WHEN statement?

View 3 Replies View Related

T-SQL (SS2K8) :: Using A Date Comparison In A Case Statement?

Mar 19, 2015

I am trying to use a date comparison in a statement using the year statement as well. Here is what I have:

Case [LastHireDate]
When YEAR([LastHireDate]) < Year(@EndYearlyDate) then '12'
When Month([LastHireDate]) = '1' then '12'
When Month([LastHireDate]) = '2' then '11'
When Month([LastHireDate]) = '3' then '10'
When Month([LastHireDate]) = '4' then '9'

[Code] ....

When I am looking at it [LastHireDate] is showing that red line underneath. The < symbol has a red line and @EndYearlyDate has a red line. I can not seem to get them to clear and am, wondering what I am missing. When I execute the error comes up that it does not like the < sign in there.

Here is the full piece that the Case resides in:

Insert _Test
SELECT
EmpNo,
PersonIdNo,
REPLACE(PersonTaxIdNo,'-',''),
LastName,
FirstName,

[code]......

View 3 Replies View Related

SQL Server 2008 :: Date Manipulation And CASE Statements

Mar 1, 2015

I have a question on date manipulation functions and CASE statements

My sql is passed the following parameter's and performs a select using a manipulation on these date param's to get a start and end date range depending on the conditions;-

monthColHeader = eg 'Feb 2015'
defaultStartDate and defaultEndDate
filterStartDate and filterEndDate.

These are my conditions;-

if defaultStart and End = filterStart and End use monthColHeader for the date range
if defaultStart and End != filetrStart and End AND the month/year of filterStart and filterEnd match then use the filterStart & End month/Year with the monthColHeader to get the date range
if defaultStart and End != filetrStart and End AND the month/year of filterStart and filterEnd DON't match use filterStart Day and monthColHeader for our start date and monthColHeader for our end date.

When I say use monthColHeader I mean like this;-

(r.dbAddDate >= (CAST('@Request.monthColHeader ~' AS DATETIME)) AND r.dbAddDate < DATEADD(mm,1,'@Request.monthColHeader ~'))

This sql works for converting say 'Feb 2015' to '2015-02-01' & '2015-02-28'....

View 1 Replies View Related

Transact SQL :: Case Statement For A New Column Based On Date And Username Columns

Sep 2, 2015

Below is the SQL Query i am currently having

SELECT IG_FinancialTransactionSummary.ClaimNum,IG_FinancialTransactionSummary.TransactionCode,
IG_FinancialTransactionSummary.TransactionDate,IG_FinancialTransactionSummary.Username,
FinancialTransactionSummaryTest.ClaimNum,FinancialTransactionSummaryTest.TransactionAmount,
FinancialTransactionSummaryTest.UserName--,FinancialTransactionSummaryTest.TransactionDate

[Code] ....

And here is the result dataset

ClaimNumTransactionDateUsername ClaimNum TransactionAmountUserName
2000074 20150209jerry.witt 2000074 -10000DATAFIX INSERTED ON 20150626 AT 162152493 LOCAL
2000074 20150626DATAFIX INSERTED ON 20150626 AT 162152493 LOCAL 2000074 -10000DATAFIX INSERTED ON 20150626 AT 162152493 LOCAL

[Code] .....

So,if we look at the result set, we notice 2 conditions where the IG_FinancialTransactionSummary.Username is like 'Data' and if we see the transaction date then sometimes that is the max transaction date or sometimes there are transactions that happened after but that doesn't have like '%data%' in username . So, i need to add a new column to my sql query which should basically verify if the username is like '%data%' and if that is the max(transaction date) or even if there are any transactions after that doesn't have like '%data%' then YES else No.

View 13 Replies View Related

Case Statement - Calculate No Of Days Based On User Input Start And End Date

Jan 5, 2015

I have to produce a report to calculate no of days based on user input start date and end date. I have tried to explain below.

say for eg: in the tables I have emp name
user 'Phani' started work from - EStart 20/11/2014EEnd 10/01/2015 - total days --datediff
within his work period he did different roles:

PhaniMarketing (prSt Date) 20/11/2014prE date (28/11/2014) Total 9 days
PhaniAdmin (prSt Date) 29/11/2014prE date (20/12/2014) Total 22 days
PhaniCRM (prSt Date) 20/12/2014prE date (10/01/2015) Total 22 days
Total days 53 Days

For this :

I calculated datediff + 1 and got sub jobs days BUT

say financial director wants to see Title of 'Sub Jobs' with 'Days' from 1st Dec to 31st Dec

so on paper I calulated as :

1-31 Dec 2014
PhaniMarketing NULL (Do not fall in Req Dt)
PhaniAdmin 20 (Deduct 2 days of Nov & calculated 20 days of Dec)
PhaniCRM 11 (Deduct 20 days of Nov and deduct 11 days of Jan so for Dec , we got 11 days)
Total days 31

HOW CAN I USE Case statement to calculate days for given start date and end date. I have to include all three totals, 1 for Job dates, 2, subjobs dates, 3 cal of days for a requested period.

View 4 Replies View Related

SQL Server 2008 :: Change Text Format From Case Sensitive To Case Insensitive?

Aug 31, 2015

How can I change my T-SQL text editor from text sensitive to text insensitive?

View 2 Replies View Related

Case Insensitivity Is On Server Wide: Tables Render Case Sensative...

Jan 6, 2005

Hello:

I have created an SQL server table in the past on a server that was all case sensative. Over time I found out that switching to a server that is not case sensative still caused my data to become case sensative. I read an article that said you should rebuild your master database then re-create your tables. So after rebuilding the master database, a basic restore would not be sufficient? I would have to go and manually re-create every single table again?

Any suggestions?

View 4 Replies View Related

Case Insensitive Searching In Sql Server 2000 When It's Case Sensitive

May 4, 2007

Can someone point me to a tutorial on how to search against a SQL Server 2000 using a case insensitive search when SQL Server 2000 is a case sensitive installation?
 
thanks in advance.

View 3 Replies View Related

SQL 7.0 And SQL 6.5 Differences

Nov 22, 1998

I am curious to what major differences there are between these two versions.
Trying to decide whether or not to purchase the SQL 6.5 training kit from Microsoft or not. If the code and utilities are the same, then I could probably still learn from the 6.5 version. Any thoughts, suggestions will be greatly appreciated.

Thanks

View 3 Replies View Related

What's The Differences?

Aug 12, 2004

What is the differences between SQL Server Desktop Engine and SQL Server Standard Edition???

Thanks

Lystra

View 3 Replies View Related

SQL CE 3.01 And 3.5 Differences

Feb 13, 2008

Hi,

I am having the following problem AFTER converting to VS2008 from VS2005 and SQLCE 3.5 from 3.01:

SQL CE db file has a table called Court0 with various columns of type float. I populate the values by copying floats from another table/tables. I do this via ado.net using this code snippet:


foreach (DataColumn column in this.mycourtsDataSet1.Tables[tableName].Columns)
{
string columnName = column.ColumnName.ToString();
string columnValue = aRow[0][columnName].ToString();
object cValue = aRow[0][columnName];


if (columnName.Remove(1) == "T" && !string.IsNullOrEmpty(columnValue))
{
// Add the value to the Court0 table.

DataRow[] bRow = this.mycourtsDataSet1.Tables["Court0"].Select("BookingPeriod = '" + columnName + "'");
if (bRow.Length > 0)
{
double colValue = Convert.ToDouble(cValue);
//bRow[0][tableName] = Convert.ToInt32(columnValue);
========> bRow[0][tableName] = colValue; <==== colValue is '1055.01'
}
}
}
}

This works fine in VS2005/CE3.01 BUT not in VS2008/CE3.5

In CE3.5, the value entered into the cell looses it's decimal value.

For example, '1055.01' becomes '1055.0' in CE3.5 .

Can someone explain to me why the conversion stuffs up in CE3.5 and what do I do to fix it.

Thanks,

View 1 Replies View Related

HELP! Case Insensitive Database On Case Sensitive Server

Aug 17, 2005

We need to install CI database on CS server, and there are some issueswith stored procedures.Database works and have CI collation (Polish_CI_AS). Server hascoresponding CS collation (Polish_CS_AS). Most queries and proceduresworks but some does not :-(We have table Customer which contains field CustomerID.Query "SELECT CUSTOMERID FROM CUSTOMER" works OK regardless ofcharacter case (we have table Customer not CUSTOMER)Following TSQL generate error message that must declare variable @id(in lowercase)DECLARE @ID INT (here @ID in uppercase)SELECT @id=CustomerID FROM Customer WHERE .... (here @id in lowercase)I know @ID is not equal to @id in CS, but database is CI and tablenames Customer and CUSTOMER both works. This does not work forvariables.I suppose it is tempdb collation problem (CS like a server collationis). I tried a property "Identifier Case Sensitivity" for myconnection, but it is read only and have value 8 (Mixed) by default -this is OK I think.DO I MISS SOMETHING ????

View 4 Replies View Related

Doing A Case-sensitive Query In A Case-insensitive Database

May 29, 2008

I am working in a SQL server database that is configured to be case-insensetive but I would like to override that for a specific query. How can I make my query case-sensitive with respect to comparison operations?

Jacob

View 5 Replies View Related

Transact SQL :: Upper Case To Lower Case Conversion

May 4, 2015

I have column with value of all upper case, for example, FIELD SERVICE, is there anyway, I can convert into Field Service?

View 7 Replies View Related

Inner Join Differences

Jul 4, 2006

Table struct (table1 and table2):
areacode
phonenumber
phonenumber2 (combined areacode + phonenumber) (actual column)
------------------------------------------------------------

select x.areacode, x.phonenumber from table1 as x
inner table2 as y
on x.AreaCode = y.AreaCode and x.phonenumber = y.phonenumber

result: 0

select x.areacode, x.phonenumber from table1 as x
inner join table2 as y
on x.phonenumber2 = y.phonenumber2

result: 100

select (x.areacode + x.phonenumber) as phone from table1 as x
inner join table2 as y
on (x.areacode + x.phonenumber) = (y.areacode + y.phonenumber)

result: 0


WHat's the difference between those queries? Why can't I get a result from the 1st and 3rd query?

View 9 Replies View Related

Database Differences

Feb 5, 2004

We have a database that when an update is released (and this is very often) the release notes don't cover most of the actual changes. Every time groups of our custom queries and reports get broken due to database changes. Does anyone know how to compare two databases and get a report of the differences between them? I can either have the two versions on the same server or on different servers if that makes a difference.

I'm hoping for something where you input @oldversion, @newversion

and return is

@oldversion, tblname, fieldname, char(8)
@newversion, tblname, fieldname, varchar(8)
@oldversion, tblname, [Null], [Null]
@newversion, tblname, fieldname, int
@oldversion, [Null]
@newversion, tblname

also any changes in dependancies

Thanks
Brent

View 8 Replies View Related

Rounding Differences

Feb 20, 2004

I have just converted some Access VBA code to a sproc. I'm finding that for some reason the rounding is different:
eg.
ROUND(17 * 97995 / 1000,2) = 1665.915 before Rounding

SQL SProc: 1665.91 Rounds down
ADP VBA: 1665.92 Rounds up

Does this make sense?

View 11 Replies View Related

Differences Between Dbs On Different Servers

Jul 7, 2003

as promised:


--sp_addlinkedserver @server = '____________'
--sp_addlinkedserver @server = '____________'
--select * from sysservers


--sp_addlinkedserver
-- '____________',
-- 'Oracle',
-- 'MSDAORA',
-- 'ORC1'

--Select * from ___________.ORC1.dbo.sysobjects

/* Objects in Company1 Missing in Company2 */
Select 'Table Objects in Company1 but are not in Company2'
select Left(a.name,30), a.refdate from sysobjects a
Where a.xtype = 'U'
and a.name like 'TBL%'
and Not Exists (Select 1 From ____________.dbname.dbo.sysobjects b where a.name = b.name)

/* Objects in Company2 Missing in Company1 */
Select 'Table Objects in Company2 but are not in Company1'
select Left(a.name,30), a.refdate from ____________.dbname.dbo.sysobjects a
Where a.xtype = 'U'
and a.name like 'TBL%'
and Not Exists (Select 1 From sysobjects b where a.name = b.name)

/* Column Differences */

Select 'Column Differences between like named tables'

select Left(x.TabName,30) as TableName, Left(x.ColName,30) as ColumnName
, Left(x.DataType,15) as Company1DataType, x.length as Company1Length, x.refdate as Company1RefDate
, Left(y.DataType,15) as Company2DataType, y.length As Company2Length, y.refdate as Company2RefDate
from
( Select a.name as TabName, b.name as ColName, b.length, c.name as DataType, a.refdate
from sysobjects a, syscolumns b, systypes c
where a.id = b.id
and b.xusertype = c.xusertype
and a.xtype = 'U' and a.name like 'TBL%') As x
, ( Select a.name as TabName, b.name as ColName, b.length, c.name as DataType, a.refdate
from ____________.dbname.dbo.sysobjects a, ____________.dbname.dbo.syscolumns b, ____________.dbname.dbo.systypes c
where a.id = b.id and a.xtype = 'U'
and b.xusertype = c.xusertype
and a.name like 'TBL%') As y
Where x.TabName = y.TabName
and x.ColName = y.ColName
and (x.length <> y.length or x.DataType <> y.DataType)

/* Column Differences */
Select 'Column in Company1.com not in Company2'

Select Left(a.name,30) as TableName, Left(b.name,30) as ColumnName, b.length, c.name, a.refdate
from sysobjects a, syscolumns b, systypes c
where a.id = b.id
and b.xusertype = c.xusertype
and a.xtype = 'U'
and a.name like 'TBL%'
and Not Exists (
Select 1
from ____________.dbname.dbo.sysobjects d, ____________.dbname.dbo.syscolumns e
where d.id = e.id
and a.xtype = 'U'
and a.name like 'TBL%'
and a.name = d.name
and b.name = e.name)
Order by 1, 2

/* Column Differences */
Select 'Column in Company2 not in Company1.com'

Select Left(a.name,30) as TableName, Left(b.name,30) as ColumnName, b.length, c.name, a.refdate
from ____________.dbname.dbo.sysobjects a, ____________.dbname.dbo.syscolumns b, ____________.dbname.dbo.systypes c
where a.id = b.id
and b.xusertype = c.xusertype
and a.xtype = 'U'
and a.name like 'TBL%'
and Not Exists (
Select 1
from sysobjects d, syscolumns e
where d.id = e.id
and a.xtype = 'U'
and a.name like 'TBL%'
and a.name = d.name
and b.name = e.name)
Order by 1, 2





--Select 'Table Objects that are still in use in both Company2 and Company1'
--select Left(a.name,30), a.refdate from sysobjects a, ____________.dbname.dbo.sysobjects b
--where a.name = b.name and a.xtype = 'U'







Brett

8-)

View 1 Replies View Related

Differences Between .sqlexpress And C:abc.mdf

Apr 2, 2008



I saw some demo-codes ,introducing sqlconnection class, sqlcommand class and etc, are involed .sqlexpress and c:abc.mdf.


so , I am quite confuse what's the deferences between .sqlexpress and c:abc.mdf

Thanks

View 1 Replies View Related

Can You Use Replication From A Case Sensitive Db To A Case Insensitive Db?

Aug 19, 2007

I am curious with using replication in sql server 2005 one way from db A (source) replicating to db B(destination) in which db A has a collation of CS and db B has a collation of CI.  Will there be any problems with this scenario? Thanks in advance! 

View 2 Replies View Related

Problem Using Result From CASE In Another CASE Statement

Nov 5, 2007

I have a view where I'm using a series of conditions within a CASE statement to determine a numeric shipment status for a given row. In addition, I need to bring back the corresponding status text for that shipment status code.

Previously, I had been duplicating the CASE logic for both columns, like so:




Code Block...beginning of SQL view...
shipment_status =
CASE
[logic for condition 1]
THEN 1
WHEN [logic for condition 2]
THEN 2
WHEN [logic for condition 3]
THEN 3
WHEN [logic for condition 4]
THEN 4
ELSE 0
END,
shipment_status_text =
CASE
[logic for condition 1]
THEN 'Condition 1 text'
WHEN [logic for condition 2]
THEN 'Condition 2 text'
WHEN [logic for condition 3]
THEN 'Condition 3 text'
WHEN [logic for condition 4]
THEN 'Condition 4 text'
ELSE 'Error'
END,
...remainder of SQL view...






This works, but the logic for each of the case conditions is rather long. I'd like to move away from this for easier code management, plus I imagine that this isn't the best performance-wise.

This is what I'd like to do:



Code Block
...beginning of SQL view...
shipment_status =
CASE
[logic for condition 1]
THEN 1
WHEN [logic for condition 2]
THEN 2
WHEN [logic for condition 3]
THEN 3
WHEN [logic for condition 4]
THEN 4
ELSE 0
END,


shipment_status_text =

CASE shipment_status

WHEN 1 THEN 'Condition 1 text'

WHEN 2 THEN 'Condition 2 text'

WHEN 3 THEN 'Condition 3 text'

WHEN 4 THEN 'Condition 4 text'

ELSE 'Error'

END,
...remainder of SQL view...


This runs as a query, however all of the rows now should "Error" as the value for shipment_status_text.

Is what I'm trying to do even currently possible in T-SQL? If not, do you have any other suggestions for how I can accomplish the same result?

Thanks,

Jason

View 1 Replies View Related

Temp Table Differences

Jun 2, 2005

What's the difference between using CREATE TABLE #TempTable and DECLARE @Table TABLE for temp tables and are there any advantages or disadvantages to using one over the other?Thanks

View 4 Replies View Related

Query Run Time Differences

Mar 14, 2002

I have a server with two test instances of a data base. I have a query which creates a temp table, inserts 29 rows, perform 4 update queries to add counts and then dumpps out the results. This entire query script runs 1.33 minutes on one instance and 2.5 minutes on the other. On the production server this query now runs in 9 seconds. If I run any one of the test updates individually they execute under 2 seconds, just like the production server.
THe results are repeatable.

All are SQL 7 with all service packs on NT4 sp6. Both test data bases are backups of production from last week. I suspect some kind of caching/buffer problem, but I do not know what to look for. I am not a DBA so I have no idea what role TEMPDB plays may play in this.

Can anyone give us ideas on where to look for the performance difference? Will our impending upgrade to SQL2K solve this problem or make it worse? Any ideas would be appreciated.

View 1 Replies View Related

Is There Any Tool To See The Differences In Two Databases.

Mar 29, 2002

Hi,

Is there any tool to find the differences between the two databases. I would like to know the differences in developmental server and Production server. if the developers create any new objects, I want to migrate them to production server.

Can we do it in sql server 200 or do we need to have separate tool.

Thanks in advance.

View 2 Replies View Related

Performance Differences Between Queries...

Sep 13, 2004

I am updating a db with data from a file, in this data we have new info, info that has been updated and info that is to be removed from the db.
Now I was wondering which approach results in better performance/shorter executin time:

1. first update excisting values, then insert new ones, and last delete cancelled data

or

2. delete cancelled data and data that will be updated, then insert new and updated info

I get all this data from a file, in that file all rows are similar and there is one column that defines if the data is new, updated or to be deleted (thus all the updates also include the information for the enty that has not been altered).


// Pati

View 4 Replies View Related

Differences Between 6.5 And 2000 Inserts

Oct 18, 2005

Hi Guru's,

I am kind of baffeled. I have a table with a column of 8 varchar in 2000
and the same in 6.5. When I insert into 2000 with a data length of more than 8 chars via Cold Fusion into the table, it fails. The same Cold Fusion
program inserts into the 6.5 table, but truncates the data but does not fail.
Does anyone know why this happens. Thanks, Newbie.

View 1 Replies View Related

Calculate Differences Between Two Dates

Sep 9, 2014

How can we calculate the difference between two dates (years, months and days)

example:

between '01 / 01/2011 'and '05 / 04/2014' I would have years, months and days

View 1 Replies View Related

Values Differences Between Days?

Jan 22, 2015

I have a SQL Server 2005 table titled "Journeys" as follows:

+---------------+
| Journeys |
+---------------+
| JourneyID |
| PlateNumber |
| DepartureDate |
| DepartureKM |
| ArrivalDate |
| ArrivalKM |
+---------------+

The table contains the following sample data:

+------------+--------------+----------------+--------------+--------------+-----------+
| JOURNEYID | PLATENUMBER | DEPARTUREDATE | DEPARTUREKM | ARRIVALDATE | ARRIVALKM |
+------------+--------------+----------------+--------------+--------------+-----------+
| 1 | ABC-123 | 01-01-2015 | 10000 | 01-02-2015 | 10200 |
| 2 | ABC-123 | 01-02-2015 | 10210 | 01-03-2015 | 10500 |
| 3 | ABC-123 | 01-03-2015 | 10500 | 01-04-2015 | 10650 |
| 4 | ABC-123 | 01-04-2015 | 10607 | 01-05-2015 | 10900 |
| 5 | XYZ-999 | 01-15-2015 | 30200 | 01-16-2015 | 30400 |
| 6 | XYZ-999 | 01-16-2015 | 30405 | 01-17-2015 | 30600 |
| 7 | XYZ-999 | 01-17-2015 | 30600 | 01-18-2015 | 30750 |
| 8 | XYZ-999 | 01-18-2015 | 30752 | 01-19-2015 | 30920 |
+------------+--------------+----------------+--------------+--------------+-----------+

I want to generate a query that returns a the following results with an extra column named 'KMDifference' which is the difference between 'ArrivalKM' from last day and 'DepartureKM' from today.

Desired results:

+-------------+---------------+-------------+-------------+-----------+--------------+
| PlateNumber | DepartureDate | DepartureKM | ArrivalDate | ArrivalKM | KMDifference |
+-------------+---------------+-------------+-------------+-----------+--------------+
| ABC-123 | 01-01-2015 | 10000 | 01-02-2015 | 10200 | 0 |
| ABC-123 | 01-02-2015 | 10210 | 01-03-2015 | 10500 | 10 |
| ABC-123 | 01-03-2015 | 10500 | 01-04-2015 | 10650 | 0 |
| ABC-123 | 01-04-2015 | 10607 | 01-05-2015 | 10900 | 7 |
| XYZ-999 | 01-15-2015 | 30200 | 01-16-2015 | 30400 | 0 |
| XYZ-999 | 01-16-2015 | 30405 | 01-17-2015 | 30600 | 5 |
| XYZ-999 | 01-17-2015 | 30600 | 01-18-2015 | 30750 | 0 |
| XYZ-999 | 01-18-2015 | 30752 | 01-19-2015 | 30920 | 2 |
+-------------+---------------+-------------+-------------+-----------+--------------+

[URL]

View 4 Replies View Related

Calculate Differences Between Records?

Feb 9, 2015

I would like to calculate the date difference between two records:

IDStartEnd
12/9/15 13:28:412/9/15 13:28:46
22/9/15 13:29:032/9/15 13:29:12
32/9/15 13:29:172/9/15 13:29:21
42/9/15 13:29:272/9/15 13:29:31

So I need to find the difference between two consecutive records and put the result in a new column called Downtime. For example:

Record 2 Start (2/9/15 13:29:03) - Record 1 End (2/9/15 13:28:46) = 0:00:17
Record 3 Start (2/9/15 13:29:17) - Record 2 End (2/9/15 13:29:12) = 0:00:05
Record 4 Start (2/9/15 13:29:27) - Record 3 End (2/9/15 13:29:21) = 0:00:06
and so on…

Also what do I do about the 1st record since there is no previous record to subtract from?

So far I have this code in my query to generate my table: SELECT Start, End FROM group_table3

My desired output should look like this:

IDStartEndDowntime
12/9/15 13:28:412/9/15 13:28:46#VALUE!
22/9/15 13:29:032/9/15 13:29:120:00:17
32/9/15 13:29:172/9/15 13:29:210:00:05
42/9/15 13:29:272/9/15 13:29:310:00:06

View 4 Replies View Related







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