Create Values From Ranges

Jun 14, 2012

I'll keep the analogy as basic as possible, but lets say we sell vouchers. The vouchers are individually numbered.

We sell the vouchers in batches, and are stored in the DB as one record per sale with a range of the vouchers sold (so they scan the first and last voucher number to get the range)

E.g.

Table1
SalesID Description From To
SalesID0001 Batch of paper 100001 100015
SalesID0002 More paper 100016 100150

The vouchers come back in individually however, so we might get voucher 100011 back and is stored in another table as an individual item.

I'm trying to write a report which shows which vouchers have not come back yet and I'm struggling since the data is stored in ranges not on an individual basis...?

My thinking is leading me to maybe create a temp table where I can convert those ranges into real numbers....which I'll be able to more easily compare - but how I might do that.

(Example output from above example

TempTable
SalesID Description Voucher
SalesID0001 Batch of paper 100001
SalesID0001 Batch of paper 100002
SalesID0001 Batch of paper 100003
SalesID0001 Batch of paper 100004
SalesID0001 Batch of paper 100005
etc, etc)

View 2 Replies


ADVERTISEMENT

Get The Date Ranges For Constant Values.

May 31, 2008

I have a table with date like this.

InstId--Date----Readings
--1---10/12/2008--10
--1---11/12/2008--10
--1---12/12/2008--10
--1---13/12/2008--9
--1---14/12/2008--10
--1---15/12/2008--10
--1---16/12/2008--10
--1---17/12/2008--10
--2---05/03/2008--8
--2---06/03/2008--6
--2---07/03/2008--8
--2---08/03/2008--8
--2---09/03/2008--8
--2---20/03/2008--8

Guys I want to get the date ranges instrument wise for which the instrument readings are constant.

For example for instrument 1 the readings are constant i.e 10 from 10/12/2008
till 12/12/2008 & then again it is constant from 14/12/2008 till 17/12/2008.
Same goes for instrument id 2.It is constant from 07/03/2008 till 20/03/2008.
I need to get the output like this.

StartDate EndDate Readings
10/12/2008 12/12/2008 10
14/12/2008 17/12/2008 10
17/03/2008 20/03/2008 8

Thanks for any help.

View 10 Replies View Related

How To Compare Alphanumeric Values Ranges Using Select Query

Nov 6, 2007

Hi All ,



I am having a table which contain data in below form



id startvalue endvalue

1 12:00a 12:29a

2 12:30a 12:59a

3 1:00a 1:29a

4 1:00p 1:29p

5 2:00a 2:29a



Through SQL query I want to select the id column value for the row returned for the following query



select id from mytable where '1:24a' >= startvalue and '1:24a' <= endvalue



Idea is I will pass a literal value that lies between the startvalue (nvarchar column) and endvalue (nvarchar column) to fetch the id of the row returned, which should be 3 But when I run the query it returns me 2 rows for id 3 and 4.


I believe this is because I am trying to compare nvarchar columns with ">=" and "<=" operators.



Can anyone suggest how i can select the correct value or how to do this.


Thanks,
Ashish

View 2 Replies View Related

Boolean: {[If [table With This Name] Already Exists In [this Sql Database] Then [ Don't Create Another One] Else [create It And Populate It With These Values]}

May 20, 2008

the subject pretty much says it all, I want to be able to do the following in in VB.net code):
 
{[If [table with this name] already exists [in this sql database] then [ don't create another one] else [create it and populate it with these values]}
 
How would I do this?

View 3 Replies View Related

T-SQL (SS2K8) :: Create Union View To Display Current Values From Table A And All Historical Values From Table B

May 6, 2014

I have 2 identical tables one contains current settings, the other contains all historical settings.I could create a union view to display the current values from table A and all historical values from table B, butthat would also require a Variable to hold the tblid for both select statements.

Q. Can this be done with one joined or conditional select statement?

DECLARE @tblid int = 501
SELECT 1,2,3,4,'CurrentSetting'
FROM TableA ta
WHERE tblid = @tblid
UNION
SELECT 1,2,3,4,'PreviosSetting'
FROM Tableb tb
WHERE tblid = @tblid

View 9 Replies View Related

Need To Create A Table With P-values

Dec 4, 2013

I need to create a table with P-values (from statistical t-test).The table should have the following 3 columns: DF (degree of freedom), X, P-value. P-value can be calculated in Excel using the following function : T.DIST.RT(X,DF)

Is there a built-in function in PL/SQL to calculate the p-value ?How can I calculate it without using an Excel ?[It will be a 17M records table- 0.00<X<17.00, 1<DF<10000) ]

View 4 Replies View Related

For XML: Create Elements Using Cell Values

Aug 5, 2005

Hi All,If have a sql table with 2 columns and 2 rows with values[["col1row1","col2row1"],["col1row2","col2row2"]].Using t-SQL with "for xml"How can i create a xml where the cell values (not column names) appearas elements?eg:<col1row1>col2row1</col1row1><col1row2>col2row2</col1row2>Thanks,slyi

View 12 Replies View Related

Gettting Primary Key Values In A DML CREATE TRIGGER

Jun 10, 2008

I would like to get the primary key values in a DML CREATE TRIGGER as follows:
CustomerID = 12 AND InvoiceID = 50
I create the DML trigger for UPDATE and DELETE only, how do I retrieve the values as above ?
Jon Galloway provided a sample in http://weblogs.asp.net/jgalloway/archive/2008/01.aspx but the Primary Key Field and Primary Key Value were inserted into separate columns while I need to combine the Primary Key Field and Primary Key Value into 1 single field, using his example, I want to form the primary key as:
ScoreId = 423
ScoreId = 3064
etc.
Note that his example only show a single primary key in a table whereas I need to handle multiple primary keys in a table.
 

View 4 Replies View Related

Delete Record Where Values Exist, Else Create Them..

Oct 3, 2000

Dear friends,

I am thinkking there has to be away to do this in a SQL
statement.

can't you do some kind of...

Create Procedure sp_update_users
@User_Id Int,
@Title_Id Int

AS
UPDATE USERS
DELETE WHERE @User_ID = User_Id and @Title_Id = @Title_Id
ELSE
INSERT INTO USERS VALUES (@User_ID,@Title_Id;)

View 3 Replies View Related

How To Create A Matrix Of Values From A Single Table

Aug 28, 2013

I'm a real novice user and I we use SQL Server. I have a table called TableLog that has the 4 columns. The first column is repeated x number of times for each value in the second column. I'd like to see this information put into a matrix where I could tell if there are any missing intersections. In addition, I need to insert a WHERE clause that says "BETWEEN 20090000 AND 20100000" for the first and second columns.

Example data in the table:

ID1 ID2 MRSSI
100 200 63
100 300 63
200 100 63
200 300 63
300 100 63

Desired matrix: P = Pass and F = Fail

100 200 300
100 n/a P P
200 P n/a P
300 P F P

From the example data, there's no intersection for 300 and 200 so a F is displayed.

View 3 Replies View Related

Can DTS Automatically Create Primary Key Values Upon Export?

May 5, 2004

I have two practice tables I have created and want to export the values of one into the source table. I want to know if I can export into a table and have the destination table automatically give a primary key value to a record? I haven't been able to figure this out even after fiddling with the "Enable identity insert" checkbox under the Column Mappings tab. I have created source tables with and without primary keys and neither works because of the fact that I need to have a value for a primary key in order to INSERT into the destination.

Do I have to copy the source records into a staging table and assign the PK values myself by hand? This can't be the answer.

ddave

View 2 Replies View Related

How To Create A Column Group Using Two Field Values?

Mar 11, 2008



Hello Friends,
I am creating a report in which I want to create group column using two field value. Is it possible to do so? We have a requirement in which we are fetching data from two different hierarchy.



A B C D E F G H I J K
L 1 2 3....................4 5
M .............................
N .........................
O .......................
P


The report matrix look like the above one. The elements A,B,C are coming from one hierarchy and D,E,F,G,H,I,J,K are coming from other hierarchy. But i have created one data set to fetch the values for the report. But while creating the column group I am getting both two diff fields so I am not able to use it in single Column group and I want to use only one column group.

Can anybody help me out to solve this issue?

View 1 Replies View Related

Can We Create Distinct Values For Document Map On A Particular Level?

Apr 16, 2007

Hi, all experts here,

Thank you very much for your kind attention.

I am having a question about document map on SQL Server 2005 Reporting Services. I found one problem with the values retrived for the document level. That is, the values are not distinct, they are duplicate for the document level. Is it possible for us to get the distinct values for a particular document level? Hope my question is clear for your help.

Thank you very much in advance for your help and advices. I am looking forward to hearing from you.

With best regards,

Yours sincerely,

View 3 Replies View Related

Create Trigger To Check Values At Insert/update

Feb 10, 2004

I have never used triggers before and I have tried to solve one problem. If I have the column "currency" in a table and want to make sure that the entered value i valid in relation to another table that contains valid currency formats, I did it like this:

---------------------------------
CREATE TRIGGER [trigger_checkCurrency] ON [dbo].[Client]
FOR INSERT, UPDATE
AS
declare @currency as char(50)
declare @country as char(50)

declare cur cursor for SELECT currency, country
FROMinserted

OPEN cur
fetch cur into @currency, @country
WHILE @@FETCH_STATUS = 0
BEGIN
if not exists(select * from listinfoid where listname = 'currency' and listid = @currency)
begin
set @currency = (cast(@currency as varchar (3)) + ' is not a valid currency')
CLOSE cur
DEALLOCATE cur
RAISERROR (@currency,16,-1) with log
return
end
if not exists(select * from listinfoid where listname = 'country' and listid = @country)
begin
set @country = (cast(@country as varchar (3)) + ' is not a valid contry')
CLOSE cur
DEALLOCATE cur
RAISERROR (@country,16,-1) with log
return
end
else
fetch cur into @currency, @country

END
CLOSE cur
DEALLOCATE cur
update Client set currency = UPPER(currency), country = UPPER(country)
---------------------------------



I use a cursor to handle multiple rows in an update query.
(SQL2000-server)

Is there an easier och better way to do this?
I´m a bit unsure of this code.

Thanx!

/Erik

View 2 Replies View Related

Analysis :: Create A Calculated Set From Union Of Values In Two Sets?

Oct 26, 2015

I have the following MDX Query:

Select {measures.[Dollars]} on 0,
non empty
[Divisions].[Division].[All].Children *
[Cost Centres].[Cost Centre].[All].Children
[Locations].[Locations].[All].Children
on 1
From MyCube

which produced the following table:

Division
 Cost Centre
 Location
 Dollars
AA
1
X
$30.00

[code]....

What I am hoping to do is create a set out of the Union of specific values in the [Cost Centres].[Cost Centre] and [Locations].[Locations] hierarchies into a single set and use that new set in my MDX query across the columns.

Using the table and query from above, I have the following conditions that would determine the value in the set (lets call the new set 'NewSet')

When Cost Centre = 1 and Location = X Then "CustomType1"
When Cost Centre = 1 and Location = Y Then "CustomType2"
When Cost Centre = 1 and Location = Z Then "CustomType3"
When Cost Centre = 2 and Location = Y Then "CustomType4"
When Cost Centre = 2 and Location = Z Then "CustomType5"Else "Default"

Then, if I was to execute the new query:

with

set NewSet as "Some Unknown Magic Here"

Select {measures.[Dollars]} on 0,
non empty
[Divisions].[Division].[All].Children *
{NewSet}
on 1
From MyCube

I would end up with 

Division
 NewSet
Dollars
AA
CustomType1  
$166.64
AA
CustomType3 
$64.24
BB

[code]....

View 2 Replies View Related

Best Practice: Use Values In WHERE Clause Or Create And Join Temp Table ?

Dec 28, 2006

Hi,
I am using a SQL back end to dynamically populate an asp.net report/page.
As the data I'm interrogating is created from a tree control, I'm having to use a recursive function to retrieve the data into a series of ID values. This all happens at the moment in a DataTable manipulated with c# code. So my ID values end up in this datatable.
 My problem is that I am then performing a crosstab query in SQL Server 2000 and these ID are required as part of that query.
 Should I create a temp table and join this into the query or should i feed in a series of ID values into a where clause?
 Any help gratefully appreciated.
Thanks.
John

View 2 Replies View Related

Trying To Create A Proc That Will Insert Values Based On A Condition That Is Another Table

Feb 16, 2005

Can someone give me a clue on this. I'm trying to insert values based off of values in another table.

I'm comparing wether two id's (non keys in the db) are the same in two fields (that is the where statement. Based on that I'm inserting into the Results table in the PledgeLastYr collumn a 'Y' (thats what I want to do -- to indicate that they have pledged over the last year).

Two questions

1. As this is set up right now I'm getting NULL values inserted into the PledgeLastYr collumn. I'm sure this is a stupid syntax problem that i'm overlooking but if someone can give me a hint that would be great.

2. How would I go about writing an If / Else statement in T-SQL so that I can have the Insert statement for both the Yes they have pledged and No they have not pledged all in one stored proc. I'm not to familar with the syntax of writing conditional statements within T-SQL as of yet, and if someone can give me some hints on how to do that it would be greatly appriciated.


Thanks in advance, bellow is the code that I have so far:

RB



Select Results.custID, Results.PledgeLastYr
From Results, PledgeInLastYear
Where Results.custID = PledgeInLastYear.constIDPledgeInLastYear
Insert Into Results(PledgeLastYr)
Values ('Y')

View 1 Replies View Related

SQL 2012 :: Create Random Alphanumeric Characters For Primary Key Values

Feb 11, 2015

For a new project. I need to create random alphanumeric characters as primary key values when inserting a record.

eg: cmSbXsFE3l8

It can start from 4 digit characters and can grow to 6, 7 as required

The database will involve more than 10000 concurrent users.

I don't want to use guid or auto increment integer or sequence.

View 9 Replies View Related

Create WHERE Statement That Will Calculate Values From Current Fiscal Year To Last Complete Month

Feb 3, 2015

I'm trying to create a WHERE statement that will calculate values from our current fiscal year to the last complete month.I'm using code that was created for us that does the calculations for our entire fiscal years. I thought I had fixed the WHERE statement to work like we wanted last year, but it appears to be broken now after trying it again in January and February. I'm guessing my WHERE statement only works for March and up, but how to get it to work for every month. Most attempts I'm trying it's just returning very large and inaccurate values.

I included my WHERE statement below of what I originally had that worked last year. The @BeginYear/Month/etc are retrieved from a different table and @Month is just set to MONTH(GETDATE())-1.

WHERE
(YEAR(SA3.DocumentDate)=@BeginYear AND MONTH(SA3.DocumentDate)>=@BeginMonth AND MONTH(SA3.DocumentDate)<=@Month)
OR
(YEAR(SA3.DocumentDate)=@EndYear AND MONTH(SA3.DocumentDate)<=@EndMonth AND MONTH(SA3.DocumentDate)>=@Month)

View 6 Replies View Related

SQL 2005 Bug? Cannot Create Full Text Index For VARBINARY Column That's Populated With Converted NVARCHAR Values

Jul 11, 2007

Hi, I was wondering if any SQL Server gurus out there could help me...I have a table I'm trying to apply a full text catalog to, however no results are ever returned due to the text column being cataloged being of varbinary(max) that's being populated from a converted nvarchar(max) value - I've narrowed it down to this specifically, populating with non nvarchar text seems to work fine.To re-create the problem quickly...If I populate the column viaCONVERT(varbinary(max), 'test text')then there is no problem, I get results as expected.However if I populate the column viaCONVERT(varbinary(max), CAST('test text' as nvarchar(max)))no results are ever returned.Is this a bug with SQL Server 2005 Full Text Indexing? I'm happily creating full text catalogs when an nvarchar is not getting converted into a varbinary.I'm setting the Document Type column to '.html' (I've tried changing this to '.txt' in case it was a fault with the html ifilter but the problem persists so I believe I can rule this out).The reason I need to convert an nvarchar to varbinary is that the table holds multi-lingual text and I'm adding a html meta tag <META NAME="MS.LOCALE" CONTENT="ES"> to the beginning in order for the full text indexing word breaker to select the correct language to catalog the text with. The aim being to provide more relevant searches in users native languages (I've read a few articles that describe this technique, but it's the first time I've tried to apply it).Any pointers / suggestions would be greatly appreciated. Cheers,Gavin.

View 14 Replies View Related

SQL 2005 Bug? Cannot Create Full Text Index For Varbinary Column That's Populated From Converted Nvarchar Values

Jul 11, 2007

Hi, I was wondering if any SQL Server gurus out there could help me...

I have a table I'm trying to apply a full text catalog to, however no results are ever returned due to the text column being cataloged being of varbinary(max) that's being populated from a converted nvarchar(max) value.

To re-create the problem quickly...

If I populate the column via
CONVERT(varbinary(max), 'test text')
then there is no problem, I get results as expected.

However if I populate the column via
CONVERT(varbinary(max), CAST('test text' as nvarchar(max)))
no results are ever returned.

Is this a bug with SQL Server 2005 Full Text Indexing? I'm happily creating full text catalogs when an nvarchar is not getting converted into a varbinary.

I'm setting the Document Type column to '.html' (I've tried changing this to '.txt' in case it was a fault with the html ifilter but the problem persists so I believe I can rule this out).

The reason I need to convert an nvarchar to varbinary is that the table holds multi-lingual text and I'm adding a html meta tag <META NAME="MS.LOCALE" CONTENT="ES"> to the beginning in order for the full text indexing word breaker to select the correct language to catalog the text with. The aim being to provide more relevant searches in users native languages (I've read a few articles that describe this technique, but it's the first time I've tried to apply it).

Any pointers / suggestions would be greatly appreciated. Cheers,
Gavin.

UPDATE: Below is a T-SQL script you can run to demonstrate the effect I'm experiencing...




Code Snippet

-- Create test database
CREATE DATABASE FullTextTest
GO
USE FullTextTest
GO

-- Create test data table
CREATE TABLE TestTable
(
pk UNIQUEIDENTIFIER NOT NULL CONSTRAINT tablePK PRIMARY KEY,
varbinarycol VARBINARY(MAX),
documentExtension VARCHAR(5),
)
GO

-- The below single entry WILL BE FOUND (the text source is being entered directly)
INSERT INTO TestTable (pk, varbinarycol, documentExtension) VALUES (NEWID(), CONVERT(VARBINARY(MAX),'<META NAME="MS.LOCALE" CONTENT="EN">test entry 1'), '.html')

-- The bellow two entries below WILL NOT BE FOUND (the text source is taken from an NVARCHAR(MAX) value)
INSERT INTO TestTable (pk, varbinarycol, documentExtension) VALUES (NEWID(), CONVERT(VARBINARY(MAX), CAST('<META NAME="MS.LOCALE" CONTENT="EN">test entry 2' AS NVARCHAR(MAX))), '.html')
INSERT INTO TestTable (pk, varbinarycol, documentExtension) VALUES (NEWID(), CONVERT(VARBINARY(MAX), CAST('<META NAME="MS.LOCALE" CONTENT="EN">test entry 3' AS NVARCHAR(MAX))), '.html')
GO

-- Create the full text catalog
sp_fulltext_database 'enable'
GO
CREATE FULLTEXT CATALOG TEST AS DEFAULT
GO
CREATE FULLTEXT INDEX ON TestTable (varbinarycol TYPE COLUMN documentExtension LANGUAGE 1033)
KEY INDEX tablePK
GO

-- NOTE: You might need to give the catalog a chance to build before running the script below.

-- Now do a search that SHOULD RETURN 3 ROWS of data, but ONLY 1 ROW IS RETURNED
SELECT CAST(varbinarycol AS NVARCHAR(MAX)) FROM TestTable WHERE CONTAINS(varbinarycol, 'test')

View 10 Replies View Related

Ranges As Columns

Aug 10, 2006

Im trying to get a table where the columns are a range of dollars spent...


Code:


$1 - $24 $25 - $49 $50 - $74
01-12 Month 5,000 6,000 6,200
13-24 Month 7,000 8,800 9,120





-------------------------

This is what i have so far. It gives me one value. Of course I can run it a bunch of times changing the values, but im just curious if there is a way to do it all at once.

---------------------

Code:


SELECT COUNT(transaction_header.transaction_id) AS CustID
FROM transaction_header INNER JOIN
Northwind.dbo.Ttype ON
transaction_header.transaction_type =
Northwind.dbo.Ttype.transaction_type
WHERE (Northwind.dbo.Ttype.Cat2 = 'CATALOG' OR
Northwind.dbo.Ttype.Cat2 = 'ECOM') AND (DATEDIFF(mm, transaction_header.transaction_date, { fn NOW() }) < 13)
AND
(transaction_header.total_net_retail BETWEEN 1 AND 24)



Thanks,
Dynasty

View 5 Replies View Related

Grouping In Ranges

Jul 1, 2004

Table:

SomeFKID <pk>
StartDateTime <pk>
EndDateTime
SomeValue

Example Scenario:

Data is stored hourly. So there would be 24 records for today for each SomeFKID. I need to be able to pass a TimeSpan (in minutes), a StartDateTime, and an EndDateTime to a stored procedure and return totals in the date range grouped by the TimeSpan. So if I want all records today grouped by 2 hour intervals I would need to pass:
7/1/2004 00:00:00, 7/1/2004 23:59:59, 120 --> and return 12 records one for hours 0-2, one for hours 2-4, etc.

Any advice would be greatly appreciated!

Thanks in advance,

Wheatster

View 8 Replies View Related

Paratitioning Ranges

May 27, 2008

after i create a paratiotion, i want to see the ranges.
when i tried to do :

SELECT *
FROM sys.partitions
WHERE OBJECT_ID = OBJECT_ID('MyPartitionedTable')


i got the paratition data but not the ranges themselfs.
how can i do this?
thnaks in advance
peleg

Israel -the best place to live in aftr heaven 9but no one wan't to go there so fast -:)

View 1 Replies View Related

Ranges With Modifiers

Oct 27, 2014

I'm trying to write a statement that will return all records within a range. The only problem is that the records can have modifiers on them.For example, a sample range I would want would be all records between 1008 and 1120. I can't use a between statement though because these records can end in modifiers, like 1009X or 1117B. How can I search for records within a range when they have modifiers such as above?

View 1 Replies View Related

Time Ranges

Sep 24, 2007

Hello -

Building a small app for a school nurse......

Have a SP that takes 2 parameters (@login, @logout) both in the form of "convert(varchar,@Login,108)" or 08:00 AM, etc

What I need to do is then check to see:
1. What period did they login in?
2. What period did they logout in?
3. How much time in a period did they actually miss?

The ranges look like:
Set @Period1Start='08:20 AM'
Set @Period1End='09:10 AM'
Set @Period2Start='09:15 AM'
Set @Period2End='10:00 AM'
...
...
...


So.....
if @login = 08:30 AM and @logout = 08:45 then they missed 15 minutes of period 1

If @login = 08:30 AM and @logout = 09:45 then they missed 40 minutes of period 1 AND 30 minutes of period 2

Not knowing all of the time functions in SQl, I am looking for some ideas on how to accomplish this.

Thanks!

Dan B

View 5 Replies View Related

Identity Ranges

Sep 21, 2005

I'm using Merge replication on a database that was designed using integer identity columns for primary keys. When I create a publisher it's great because Sql Server will create rowguid columns for me on most of the tables; actually all but one table.

View 1 Replies View Related

How To Pull From Two Date Ranges

Dec 17, 2006

Can someone please help me with this?
I need a query that will pull clients that made payments last year but not this year.
 I need the query to use date parameters so I can select any date range for the past year and the current year.
I have listed the tables and fields that might be needed: I'm hoping to do this without temp tables.
Date range is based on the tblPaymentReceipts.PaymentDate
tblClients, ClientID
tblPayment, PmtID, ClientID, Paystartdate, Paygroup
tblPaymentReceipts, PmtRcptID, PmtID,CleintID,PaymentDate,PaymentAmount

View 6 Replies View Related

Populating Data Between Ranges

Oct 3, 2007

Hi All,
I have a startdate (01/11/2007) and a enddate (01/11/2008).  I need to add dates into a table for everyday between these dates.  Can anyone help?

View 1 Replies View Related

Find Time Ranges

May 25, 2008

Find Time Ranges
I have a DateTime field, I need to find out how many records are in 8am-11am, 12pm-5pm, 6pm-7am regardless of date. How can I do this?

View 4 Replies View Related

Comparing Date Ranges

Mar 18, 2004

I have two sets of dates to work with. One is an existing booking with a start and an end date. The other is a new booking with a start and an end date. I want to compare them and calculate how much overlap there is. If the overlap is over a certain amount (say 4 days), then I want to flag the user.

Is there any thing I can use in terms of a SQL query to assist in this comparison? I'm relatively new to SQL so I'm not entirely sure what functions and keywords are available to me to make this comparison.

View 3 Replies View Related

Overlapping Integer Ranges ??

Jul 26, 2004

:confused: Dont know if this will be tough for the rest of you but for someone who is fairly new to SQL...I cannot figure it out...

I have a table:

Rownumber starttime endtime
1 l 30 l 240
2 l 40 l 120
3 l 50 l 260
4 l 1300 l 1400


Rows 1, 2, and 3 over lap with one another and I am trying to obtain the starttime and endtime values which can cover them all.

I would like to find the overlapping (starttime - endtime) ranges and accept the lowest starttime value and the highest endtime value.

Row 1: 30--------------------240
Row 2: 40--------------120
Row 3: 50----------------------260
Row 4: ...1300---------1440


I would like to include starttime-endtime ranges that do not overlap with any other integer range.

which in this case would be:

Rownumber starttime endtime
1 l 30 l 260
2 l 1330 l 1400

I was thinking of using a cursor and comparing each row to all of the other rows in the table and then setting a boolean in that row if it overlaps with another row in the table...is there a better way of doing this?

Thank you for the help!

View 14 Replies View Related

Gaps In Integer Ranges

Dec 13, 2004

hello, i have quite a challenge on my hands here and would appreciate any help. :confused:

I have a table variable that stores integer ranges representing times of the day:

select * from @reservations

room date | starttime | endtime
1 2004-12-11 0 1440 (represents an entire day in minutes)
2 2004-12-12 420 1020
3 2004-12-14 200 600
4 2004-12-15 0 200
4 2004-12-15 500 1000


I need to be able to return the minutes that are open for each room. The @reservations table shows me the times that are blocked.

I'd like to analyze each row and return an integer range representing gaps in the day, where 0-1440 represents an entire day.

Based on the @reservations table above, I'd like to write something that returns:

room date starttime endtime
2 2004-12-12 0 420
2 2004-12-12 1020 1440
3 2004-12-14 0 200
3 2004-12-14 600 1440
4 2004-12-15 200 500
4 2004-12-15 1000 1440

This result represents the times in minutes that are available.

I have no clue how to do this without using a numbers table and checking each minute in each day for each row in the table. Id like to not do that because of sheer performance reasons. There is a possiblity that I will have hundreds of rows in the @reservations table.

I was hoping someone could provide some insight as to how to approach this. Thank you ahead of time! :)

View 3 Replies View Related







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