473,387 Members | 1,374 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

t-sql query

Hi Everyone,

This is my first time here and I want to tackle the given below problem. any insight would be great

I have 2 views and want to calculate days in between 2 dates(under same column) for approx. 500 rows.

Data is like this

view 1

14 ab 01/03/2007
14 ab 11/03/2007
14 ab 23/04/2007
14 ab 30/04/2008


view 2

14 ab xyz
13 ac avc
12 ad see
1 az qwa


Result i want

14 ab 01/03/2007 2 (minus from the first day of month)
14 ab 11/03/2007 10
14 ab 23/04/2007 .
14 ab 30/04/2008 .
Feb 28 '08 #1
16 1922
Delerna
1,134 Expert 1GB
The datediff function returns the difference between two dates in whatever multiple you want. Days, months, years, hours, minutes, seconds
Feb 28 '08 #2
The datediff function returns the difference between two dates in whatever multiple you want. Days, months, years, hours, minutes, seconds


This thing I know but I want to know that how I can use that with 2 views where multiple rows exist and how to add some functionality to catch the first day of month if first record day is not that.
Feb 29 '08 #3
Delerna
1,134 Expert 1GB
I dont know the field names so I will make some up and you can adjust to suit. From your desired result a cant see vow view 2 comes in so I will ignore for this post.
View1
ID AL DTE
14 ab 01/03/2007
14 ab 11/03/2007
14 ab 23/04/2007
14 ab 30/04/2008

Expand|Select|Wrap|Line Numbers
  1. SELECT ID,AB,DTE,isnull((SELECT max(DTE) from View1 a where a.Dte<b.Dte),b.Dte)) as PrevDte
  2. FROM View1 b
  3. Order by DTE
  4.  
that will return the rows with the date from the previous record as PrevDte

now wrap that up as a subquery and do the datediff bit
Expand|Select|Wrap|Line Numbers
  1. SELECT ID,AB,DTE,datediff(d,DTE,PrevDte) as NumDays
  2. FROM
  3. (SELECT TOP 100 PERCENT ID,AB,DTE,isnull((SELECT max(DTE) from View1 a where a.Dte<b.Dte),b.Dte) as PrevDte
  4. FROM View1 b
  5. ORDER BY Dte) s
  6.  
I haven't tested that so you may have some debugging to do. Hope that helps you
Feb 29 '08 #4
Thanks for posting, your suggestions are on right track but I think that I confused you

This is what I am trying to do, if id, ab changes in view then the whole process run again and counts the days in between from start of month if start date is not 1st of month and if it is 1st then skip that part (in this case days in between would be 0) and count the days in between with next date under same id, ab. The query given by you is showing results in minus.

Here is what final output should look like

id ab dte days in between
14 ab 1/11/2007 10
14 ab 1/25/2007 14
14 ab 2/1/2007 6
15 cd 3/13/2007 12
15 cd 3/24/2007 11
15 cd 3/28/2007 4
.
.
.
.
Feb 29 '08 #5
ck9663
2,878 Expert 2GB
Thanks for posting, your suggestions are on right track but I think that I confused you

This is what I am trying to do, if id, ab changes in view then the whole process run again and counts the days in between from start of month if start date is not 1st of month and if it is 1st then skip that part (in this case days in between would be 0) and count the days in between with next date under same id, ab. The query given by you is showing results in minus.

Here is what final output should look like

id ab dte days in between
14 ab 1/11/2007 10
14 ab 1/25/2007 14
14 ab 2/1/2007 6
15 cd 3/13/2007 12
15 cd 3/24/2007 11
15 cd 3/28/2007 4
.
.
.
.
try this:

Expand|Select|Wrap|Line Numbers
  1. select id, ab, dte, NextDate, datediff(dd, dte,NextDate) as DaysInBetween 
  2. from 
  3. (select a.id, a.ab, a.dte, (select top 1 dte from yourtable b where a.id = b.id and a.ab = b.ab and a.dte < b.dte) as NextDate
  4. from yourtable a) z
  5.  
Good luck

-- CK
Feb 29 '08 #6
try this:

Expand|Select|Wrap|Line Numbers
  1. select id, ab, dte, NextDate, datediff(dd, dte,NextDate) as DaysInBetween 
  2. from 
  3. (select a.id, a.ab, a.dte, (select top 1 dte from yourtable b where a.id = b.id and a.ab = b.ab and a.dte < b.dte) as NextDate
  4. from yourtable a) z
  5.  
Good luck

-- CK

Hi CK,

everything looks working except one thing that how should I catch first day of month in this if NextDate is not first of the month when ab is changing to cd and same at the start of data.
Feb 29 '08 #7
ck9663
2,878 Expert 2GB
On your example you have this:

id ab dte days in between
14 ab 1/11/2007 10
14 ab 1/25/2007 14
14 ab 2/1/2007 6
15 cd 3/13/2007 12
15 cd 3/24/2007 11
15 cd 3/28/2007 4
Would you mind inserting the first of the month and the days in between that you are trying to do?

Thanks

-- CK
Feb 29 '08 #8
Delerna
1,134 Expert 1GB
try this. And no, I don't know why I put oder by in my first example.
Brain snap

Expand|Select|Wrap|Line Numbers
  1. SELECT ID,AB,DTE,datediff(d,DTE,isnull(PrevDte,FirstOfMonth)) as NumDays
  2. FROM
  3. (   SELECT ID,AB,DTE,
  4.            convert(char(4),year(Dte) 
  5.                + '-' +convert(char(2),month(Dte)) 
  6.                + '-01') 
  7.            as FirstOfMonth,
  8.     (SELECT max(DTE) from View1 a where a.Dte<b.Dte) as PrevDte
  9.     FROM View1 b where a.ID=b.ID and a.AB=b.AB and a.Dte>b.Dte
  10. ) s
  11.  
  12.  
Feb 29 '08 #9
On your example you have this:



Would you mind inserting the first of the month and the days in between that you are trying to do?

Thanks

-- CK

Hi CK,

I want results like this

If this is the data in table (while days in between is output) -

id ab dte days in between
14 ab 1/11/2007 10
14 ab 1/25/2007 14
14 ab 2/1/2007 6
15 cd 3/13/2007 12
15 cd 3/24/2007 11
15 cd 3/28/2007 4

I want output like this -

id ab dte days in between

1/01/2007
14 ab 1/11/2007 10
14 ab 1/25/2007 14
14 ab 2/1/2007 6
3/01/2007
15 cd 3/13/2007 12
15 cd 3/24/2007 11
15 cd 3/28/2007 4


while 1/01/2007 and 3/01/2007 should calculate automatically the daysin between whenever 14 and ab changed to 15 and cd respectively and calculate days forward instead of null on last day entry under ab or cd.

currently, your query is doing same thing but not taking this first day of month crietia and that is why null value is coming in last of each batch of ab or cd.

Thanks of all the help till now!
Feb 29 '08 #10
Delerna
1,134 Expert 1GB
OOPS I put the extra criteria in the wrong part
Expand|Select|Wrap|Line Numbers
  1. SELECT ID,AB,DTE,datediff(d,DTE,isnull(PrevDte,FirstOfMonth)) as NumDays
  2. FROM
  3. (   SELECT ID,AB,DTE,
  4.            convert(char(4),year(Dte) 
  5.                + '-' +convert(char(2),month(Dte)) 
  6.                + '-01') 
  7.            as FirstOfMonth,
  8.           (   SELECT max(DTE) 
  9.               FROM View1 a 
  10.               WHERE a.ID=b.ID and a.AB=b.AB and a.Dte<b.Dte
  11.           ) as PrevDte
  12.     FROM View1 b 
  13. ) s
  14.  
  15.  
Feb 29 '08 #11
ck9663
2,878 Expert 2GB
Hi CK,

I want results like this

If this is the data in table (while days in between is output) -

id ab dte days in between
14 ab 1/11/2007 10
14 ab 1/25/2007 14
14 ab 2/1/2007 6
15 cd 3/13/2007 12
15 cd 3/24/2007 11
15 cd 3/28/2007 4

I want output like this -

id ab dte days in between

1/01/2007
14 ab 1/11/2007 10
14 ab 1/25/2007 14
14 ab 2/1/2007 6
3/01/2007
15 cd 3/13/2007 12
15 cd 3/24/2007 11
15 cd 3/28/2007 4


while 1/01/2007 and 3/01/2007 should calculate automatically the daysin between whenever 14 and ab changed to 15 and cd respectively and calculate days forward instead of null on last day entry under ab or cd.

currently, your query is doing same thing but not taking this first day of month crietia and that is why null value is coming in last of each batch of ab or cd.

Thanks of all the help till now!
Option 1:
1. Create a new view with this query:
Expand|Select|Wrap|Line Numbers
  1.       select a.id, a.ab, DATEADD(mm, DATEDIFF(mm,0,a.dte), 0) as dte
  2.       from yourtable a left join (select b.id, b.ab, min(b.dte) as FirstTransactionDate from yourtable b group by b.id, b.ab) c
  3.          on a.id = c.id and a.ab = c.ab and datediff(dd,DATEADD(mm, DATEDIFF(mm,0,a.dte), 0),c. FirstTransactionDate) = 0
  4.       where c.id is null and c.ab is null and c.FirstTransactionDate is null
  5.       union 
  6.       select c.id, c.ab, c.dte from yourtable
  7.  
This query is getting the first day of the month based on the month of the first dte. It will then check if the first day of the month is already existing on your table to avoid duplicates. Then append the rest of your table

2. Use the same query that I posted earlier. Instead of yourtable, replace it with the name of the view you created on #1.

Option 2:
1. Replace all yourtable with the query on Option 1-#1.

-- CK
Mar 1 '08 #12
OOPS I put the extra criteria in the wrong part
Expand|Select|Wrap|Line Numbers
  1. SELECT ID,AB,DTE,datediff(d,DTE,isnull(PrevDte,FirstOfMonth)) as NumDays
  2. FROM
  3. (   SELECT ID,AB,DTE,
  4.            convert(char(4),year(Dte) 
  5.                + '-' +convert(char(2),month(Dte)) 
  6.                + '-01') 
  7.            as FirstOfMonth,
  8.           (   SELECT max(DTE) 
  9.               FROM View1 a 
  10.               WHERE a.ID=b.ID and a.AB=b.AB and a.Dte<b.Dte
  11.           ) as PrevDte
  12.     FROM View1 b 
  13. ) s
  14.  
  15.  

Hi,

Thanks for the help! After small tweaks this works as I wanted.
Mar 4 '08 #13
I don't see a reason, you should use View2 in your query when getting the # of days.

The query can go as:

[PHP]select ColumnX, datediff(dd,dateadd(mm, datediff(mm,0,getdate()),0),getdate())[/PHP]
Mar 4 '08 #14
ck9663
2,878 Expert 2GB
That's why he has the option.

-- CK
Mar 4 '08 #15
OOPS I put the extra criteria in the wrong part
Expand|Select|Wrap|Line Numbers
  1. SELECT ID,AB,DTE,datediff(d,DTE,isnull(PrevDte,FirstOfMonth)) as NumDays
  2. FROM
  3. (   SELECT ID,AB,DTE,
  4.            convert(char(4),year(Dte) 
  5.                + '-' +convert(char(2),month(Dte)) 
  6.                + '-01') 
  7.            as FirstOfMonth,
  8.           (   SELECT max(DTE) 
  9.               FROM View1 a 
  10.               WHERE a.ID=b.ID and a.AB=b.AB and a.Dte<b.Dte
  11.           ) as PrevDte
  12.     FROM View1 b 
  13. ) s
  14.  
  15.  


Hi Delerna,

Thanks for all the help in the previous post of mine and I need help again. Current output is showing results as given below from previous query and posts which we communicated but I need some modifications (i want to count 0 as "daysinbetween" if "dte" repeat itself for "ab" and "id" combination) to put 0 for duplicate dates in "daysinbetween" -

current results -

id ab dte daysinbetween

1/01/2007 --assumed first of the month
14 ab 1/11/2007 10
14 ab 1/11/2007 10
14 ab 1/11/2007 10
14 ab 1/25/2007 14
14 ab 2/1/2007 6
3/01/2007--assumed first of the month
15 cd 3/13/2007 12
15 cd 3/13/2007 12
15 cd 3/13/2007 12
15 cd 3/24/2007 11
15 cd 3/24/2007 11
15 cd 3/28/2007 4


Modified results would be -

id ab dte days in between

1/01/2007 --assumed first of the month
14 ab 1/11/2007 10
14 ab 1/11/2007 0
14 ab 1/11/2007 0
14 ab 1/25/2007 14
14 ab 1/25/2007 0
14 ab 2/1/2007 6
3/01/2007 --assumed first of the month
15 cd 3/13/2007 12
15 cd 3/13/2007 0
15 cd 3/13/2007 0
15 cd 3/24/2007 11
15 cd 3/24/2007 0
15 cd 3/28/2007 4

Thanks again!
Apr 30 '08 #16
Delerna
1,134 Expert 1GB
if you look at this data sequence

14 ab 1/11/2007 10
14 ab 1/11/2007 10
14 ab 1/11/2007 10
you can see that there is nothing to distinguish 1 row from the other.

Therefore, there is nothing to use in order to tell which row should keep its number and which should become 0.
So unless there are other fields that can be brought into the query that would make each row unique, you will need to resort to cursors.

PS
You are welcome to the help but its not a good idea to address a question to an individual expert. There are lots of other experts just as capable and lots more even more capable than I here.
You are actually limiting your chances of getting an answer. What if I decided never to come back to this site?
Just A word to the wise.
May 1 '08 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Steve | last post by:
Hi; I'm brand spanking new to sqlserver ( nice so far ). I need to make a simple data change across a list of tables. Basically replace an old date with a new date. However, the people I am...
2
by: dynoweb | last post by:
I have several *.sql files with schema/data changes to be applied to our current database. Is there a way to create a TSQL script that could be run from the SQL Query Analyzer that would...
1
by: avinash | last post by:
hi myself avi i am developing one appliacaion in which i am using vb 6 as front end, adodb as database library and sql sever 7 as backend. i want to update one table for which i required data from...
11
by: randi_clausen | last post by:
Using SQL against a DB2 table the 'with' key word is used to dynamically create a temporary table with an SQL statement that is retained for the duration of that SQL statement. What is the...
3
by: David Lozzi | last post by:
Howdy, ISSUE 1: See issue 2 below. I have a distance calculator on my site which works great. However, the users need to sort by distance, which make sense. I'm not sure how to do it other than...
16
by: David Lozzi | last post by:
Hello, I have some code that adds a new user. The new user has a checkboxlist of items which they can be associated with. I would like to send this list of items to TSQL along with the new user...
4
by: roman.ali | last post by:
Hi, I am using a .dqy file to import some rows from a sql server 2003 database to microsoft excel. Unfortunately, I have am importing more rows than excel can handle. Is there a way around...
7
by: Filips Benoit | last post by:
Dear all, Tables: COMPANY: COM_ID, COM_NAME, ..... PROPERTY: PRP_ID, PRP_NAME, PRP_DATATYPE_ID, PRP_DEFAULT_VALUE ( nvarchar) COMPANY_PROPERTY: CPROP_COM_ID, CPROP_PRP_ID, CPROP_VALUE...
1
by: mattcolley | last post by:
Hi All-- I have a column which contains an ID value. I also have a URL column (within same table) which contains a NULL value, that I am trying to update with a URL value + the value in the ID...
1
by: jabeek | last post by:
I had to write a valid TSQL query that does all the following in a transaction and will rollback if any system error is thrown. • Create the following tables Customer, Order and Address where...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.