Collating Records Based On Dates

Aug 12, 2013

I am trying to create a report where the rows of the database have fields containing customer names and dates associated with the names. I want to know for each customer how many records the customer has for specified date ranges.

SELECT [DL].[Customer], Count([DL].[Date Received]) AS [CountOfDate Received1]
FROM [DL]
WHERE ((([DL].[Date Received]) Between #12/31/2012# And #1/1/2014#))
GROUP BY [DL].[Customer];

The idea is a list of the number of records for each customer in 2013.

Ultimately my goal is to show the customer activity over multiple years.

So,
Customer Name 201120122013
Customer A123
Customer B246
Customer C543

I am trying to go down the path of a Union:

SELECT [DL].[Customer], Count([DL].[Date Received]) AS [CountOfDate 2013]
FROM [DL]
WHERE ((([DL].[Date Received]) Between #12/31/2012# And #1/1/2014#))
GROUP BY [DL].[Customer]

[Code] ....

This returns 2 columns only not the four I am looking for.

View 1 Replies


ADVERTISEMENT

SQL 2012 :: Query To Make Single Records From Multiple Records Based On Different Fields Of Different Records?

Mar 20, 2014

writing the query for the following, I need to collapse the continuity. If the termdate for an ID is one day less than the effdate of the next id (for the same ID) i need to collapse the records. See below example .....how should i write the query which will give me the desired output. i.e., get min(effdate) and max(termdate) if termdate is one day less than the effdate of next record.

ID effdate termdate
556868 1999-01-01 1999-06-30
556868 1999-07-01 1999-10-31
556869 2002-10-01 2004-01-31
556872 1999-02-01 2000-08-31
556872 2000-11-01 2004-01-31
556872 2004-02-01 2004-02-29

output should be ......

ID effdate termdate
556868 1999-01-01 1999-10-31
556869 2002-10-01 2004-01-31
556872 1999-02-01 2000-08-31
556872 2000-11-01 2004-02-29

View 0 Replies View Related

Collating Problem?

Feb 9, 2008

Hello,

I use SQL Server 2000 and a Delphi 7.0 app.
We have migrated our database recently to a new collation "Turkish_CI_AS".
Because of problems with the "i" and "I" on the Turkish alphabet, we have to make some alterations on our app.
No big deal. All working fine.

So, we send our app to partners and it begin to act "weird".

Talking to them, we discovered that the collation that they use on their database is the "Turkish_CI_AI".

Some problems that they get on their plataform when running our app are as follow:

1. When trying to open a table (using SQL via ADO components on Delphi 7) , receive the error "Item cannot be found in the collection corresponding to the correct name or ordinal".

2. When the user select one item on a DBComboBox, the information that correspond to the item are show on the DBGrid, but the item is not showed on the DBComboBox and when he try to update the information, pop up an error message "Row cannot be located for updating. Some values may have been changed since it was last read", and this is not true.

I've done some research on net for the first error, and don't understand... It appears to occour when the table name or column name that are been ask to the server don´t exist, but on our system all work well (no problems)...

Someone can say to me if this is a collation problem or is anything else? Like a wrong version on MDAC for exemple, on the other (Turkish) system?

For now, they cannot change the collation and neither can we, so, I cannot test if these errors occour on our system if we change the collation to "Turkish_CI_AI". Anyway, I don't see this like possible, because we don't use accents on table names or column names, but on the impossibility to test, it's best ask to someone that maybe knows the answer...

Any help will be welcome.

Thanks in advace.

View 1 Replies View Related

Collating All Job Failure Notification In One Place

Jan 15, 2001

Good afternoon one and all,

I have numerous jobs running on my SQL Server machine. Due to the fact that my company will not sanction an e-mail account for a machine (damn them!!) I have no way of knowing (quickly) whether a Job has failed. Does anyone hae any suggestions on how I can create a file or SQL table that is updated every time a job fails? (writing to NT application log is not an option beacause Operations refuse to trawl thru it).

TIA for any and all help

Gurmi

View 1 Replies View Related

Returning Results Based On Dates

Oct 19, 2007



I want to write a stored procedure that takes two three paramters based on a case statement determining which values are null something like this

Select InformationDate From thisTAble

Where

If @dateValue IsNot @Null
Informationdate = @dateValue
Else

Where

In this second where cluase I want to be able to pull out all the results based on a date range and i am not sure how the syntaz would go

InfomationDate IsBettween @daterangeFrom @dateRangeTwo


Any help on this i hope i was clear...thank you!

View 7 Replies View Related

CREATING TABLE USING SQL BASED ON SEQUENTIAL DATES

Jul 20, 2005

I would like to reopen this discussion. I need to create this tableusing SQL that will return this dataset.BRAID RATEDEFID MIN(BRADATE) MAX(BRADATE RATECODE PRODNAME614 14 12/1/2002 12/4/2004 Rack BeachTower Terrace618 14 12/8/2002 12/11/2004 Rack BeachTower Terrace622 14 12/15/2002 12/19/2004 Rack BeachTower TerraceI have provided the test data below and the SP I have been working with.The SP works fine as long as there are 4 seqential dates. I getunpredictable results when the count <> 4. I am also concerned on whathappens at the end of the month. For example, 1/31/2004, 2/1/2004.Does this affect the SP? I appreciate your continued support.MichaelCREATE TABLE [dbo].[BASERATEAVAIL_Tmp] ([BRAID] [decimal](18, 0) NOT NULL ,[RATEDEFID] [decimal](18, 0) NOT NULL ,[BRADATE] [datetime] NOT NULL ,[RATECODE] [varchar] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL,[PRODNAME] [varchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL) ON [PRIMARY]GOINSERT INTO dbo.BASERATEAVAIL_Tmp(BRAID, RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (614, 14, '12/1/2002', 'Rack', 'Beach Tower Terrace');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (615, 14, '12/2/2002', 'Rack', 'Beach Tower Terrace');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (616, 14, '12/3/2002', 'Rack', 'Beach Tower Terrace');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (617, 14, '12/4/2002', 'Rack', 'Beach Tower Terrace');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (618, 14, '12/8/2002', 'Rack', 'Beach Tower Terrace');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (619, 14, '12/9/2002 ', ' Rack ', ' Beach Tower Terrace ');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (620, 14, '12/10/2002', ' Rack ', ' Beach Tower Terrace ');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (621, 14, '12/11/2002', ' Rack ', ' Beach Tower Terrace ');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (622, 14, '12/15/2002', ' Rack ', ' Beach Tower Terrace ');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (623, 14, '12/16/2002', ' Rack ', ' Beach Tower Terrace ');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (624, 14, '12/17/2002', ' Rack ', ' Beach Tower Terrace ');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (625, 14, '12/18/2002', ' Rack ', ' Beach Tower Terrace ');INSERTINTO dbo.BASERATEAVAIL_Tmp(BRAID,RATEDEFID, BRADATE, RATECODE, PRODNAME)VALUES (626, 14, '12/19/2002 ', ' Rack ', ' Beach Tower Terrace ');CREATE PROCEDURE usp @n INTASSET ANSI_WARNINGS OFFSELECT MIN( braid) AS "braid",ratedefid, ratecode, prodname,MIN( CASE n WHEN 1 THEN bradate END ) AS "min_date",MAX( CASE n WHEN 0 THEN bradate END ) AS "max_date"FROM ( SELECT t1.braid, t1.ratedefid, t1.ratecode, t1.prodname,t1.bradate,COUNT( * ) % @n AS "n",( COUNT( * ) - 1 ) / @n AS "r"FROM BASERATEAVAIL_Tmp t1INNER JOIN BASERATEAVAIL_Tmp t2ON t2.bradate <= t1.bradateGROUP BY t1.braid, t1.ratedefid, t1.ratecode, t1.prodname,t1.bradate) DGROUP BY r, ratedefid, ratecode, prodnameHAVING MAX( CASE n WHEN 0 THEN bradate END ) IS NOT NULL ;Usage:EXEC usp @n = 4--Anith*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 1 Replies View Related

Transact SQL :: How To Get Four Quarter End Dates Based On Given Date

Jun 3, 2015

I have a simple following table which is having only one date column.

CREATE TABLE TEST_DATE
(
InputDate DATE
)
GO
INSERT INTO TEST_DATE VALUES('01-01-2015')
INSERT INTO TEST_DATE VALUES('06-25-2015')
INSERT INTO TEST_DATE VALUES('11-23-2014')
GO
SELECT * FROM TEST_DATE;

And the expected out put would be as follows:

I want to derive a Four Quarter End Date based on Date selected.

For Example if i select 01-01-2015 then
First Quarter End Date would be Previous Quarter End Date
Second Quarter End Date would be Current Quarter End Date
Third Quarter End Date would be Next Quarter End Date
Fourth Quarter End Date would be Next +1 Quarter End Date Like that

View 9 Replies View Related

Is There An Easier Way? Two Aggregate Fields From One Based On Dates

Oct 19, 2007

When I was looking at this I knew that I've done this same issue before without using temp tables at all but I need a push to to jar it loose.

I have a table like this:







Balance
Date

1
200
2/14/2000

2
350
2/14/2000

3
32
2/14/2000

2
723
2/14/1998

3
354
2/14/1998





1
321
2/14/2000

2
673
2/14/1998

3
581
2/14/2000

2
574
2/14/1998

3
50
2/14/2000

1
10
2/14/2000

And essentially need this.










Total Balance Before 1/1/2000
Total Balance After 1/1/2000

1
0
531

2
1970
350

3
354
663



Right now I'm splitting it into two temp tables and then joining them together.

Temp Table 1 has the sum of the balance grouped by field1 before 1/1/2000 and Temp table 2 has the after 1/1/2000 criteria.

Table 1 gets updates with field1 values from table 2 that aren't already there. And then the balance field after 1/1/2000 is merged in.

Utimately this will be used in a SPROC for a Multivalued SSRS report.

View 3 Replies View Related

Dynamic CASE Statement Based On List Of Dates

Oct 5, 2007

I have the following table of data.  I need to take a date from a large table and do the following case:CASEWhen date < date(0)     Then '0'When date between date(0) and date(1)      Then '1'When date between date(1) and date(2)     Then '2'When date >= date(3)      Then '3'What I need is to be able to read all the dates the the Date table, sort then chronologically, and build the dynamic CASE statement so that the first When statement is < Date(0) and the last When statement is >= Date(Last)I hope I am making sense.  Dates will be added to the table about once a year or so and I don't want to keep going back into the sql function and rewrite it with the latest date.  Any ideas how to manipulate these dates into a case statement?  Don't worry about the second table below.  I just wanted you to see why I need to return an int from the Case function.thanksMilton



Dates Table

Date

4/1/2003

1/1/2006

4/2/2007

Fee Table



Date
Period
Class
Fee

1
Daily
True
329

1
Half Day
True
178

1
OT
True
49

1
Hourly
True
41

1
Daily
False
156

1
Half Day
False
86

1
OT
False
27

1
Hourly
False
19

2
Daily
True
355

2
Half Day
True
192

2
OT
True
50

2
Hourly
True
44

2
Daily
False
171

2
Half Day
False
92

2
OT
False
28

2
Hourly
False
21

3
Daily
True
364

3
Half Day
True
197

3
OT
True
51

3
Hourly
True
45

3
Daily
False
175

3
Half Day
False
94

3
OT
False
29

3
Hourly
False
21

View 3 Replies View Related

Populate Dates For Parameters Based On A String Parameter

Jul 2, 2007

Hello,



My basic goal is to try to simplify inputs for the user. I have 3 parameters: Begin Date, End DAte and Duration. Duration will contain 3 choices: All, 2 Years and Range and is meant to give them a shortcut to dates as described below:

All - Would automatically populate the start date to 10/01/2005 and an end date to current date

2 Years - Would automatically populate the start date to current date minus 2 years, and the end date to current date.

Range - Would allow the user to select any dates as desired.



I'm able to get the dates to populate based on the duration field using non-queried values based on the Duration value, but the problem is that if I want to allow them to select Range the calendar control is not available and a text box is displayed.



I've tried to create some code in the properties that would populate, but I keep getting that this item is Read Only. The code I've created is as follows:

public function populateDates(Duration) as String

Select Case Duration
Case = "Range"
Report.Parameters!pBeginDate = Report.Parameters!pBeginDate
Report.Parameters!pEndDAte = Report.Parameters!pEndDAte
Case = "All"
Report.Parameters!pBeginDate = #10/01/2005#
Report.Parameters!pEndDAte = Now().Today
case = "Two"
Report.Parameters!pBeginDate = DateAdd("yyyy", -2, Now().Today)
Report.Parameters!pEndDAte = Now().Today
end select
end sub


My only goal is to give the User the 3 choices, but still keep the calendar control available, and I can't seem to do this?



suggestion please!

Thanks!

Maureen

View 6 Replies View Related

Calculating Length Of Service Categories Based On Start Dates

May 1, 2007

Ok, so I've been struggling with the logic behind this one for a while, so I thought I'd ask you guys for some ideas :)

Basically, I have the following table structure
Employee(employee_number, continuous_start_date, ...)

The problem lies in working out a summary of service categories (0-6months, 7-12months, 13-24, 25+).
I can work out the length of service in months with the following code

SELECT DateDiff(mm, continuous_start_date, GetDate()) AS 'Service in months'
FROM employee

So the first stage is to summarise the length of service into groups as mentioned above.

Then the final stage is working out how many people are in each group!

Hope I have given enough information - and please do not post a full solution - just some hints on how to get the desired result ;)

Thanks later, and in advance :p
-GeorgeV

View 14 Replies View Related

SQL 2012 :: Calculating Fiscal Week Based On Input Dates

Aug 19, 2014

I need a Query for calculating the fiscal_week based on the input dates (start_date and end_date), though I got a query from this forum, it is not giving me exact result.

the sample is in the excel file with the attachment.

In the excel:

First tab tells you the raw_data what I am using to find the Fiscal_week
Second tab tell you the data where i found the mistake, and how I am expecting the output.

I also have attached the query I have got from this forum, query I have modified for fiscal week.

View 4 Replies View Related

Transact SQL :: How To Extract Dates From A Single Column Based On Conditions

Oct 13, 2015

The data I have is as follows -

ID1    ID2     Date            Action
100   500     09/08/14     Open
100   500     09/24/14     Close
101   510     07/10/15     Open
101   510     07/19/15     Close

The output I want in a single result set is -

ID1    ID2     Open_Date   Close_Date
100    500    09/08/14      09/24/14
101    510    07/10/15      07/19/15

Any way to do this in T-SQL .

View 10 Replies View Related

Select All Records Between 2 Dates

Apr 6, 2004

I am trying to select all records added between 2 dates that the user inputs into a form and am having problems. I had this working no problems with asp but can't seem to get it working with .net. BTW I am using SQL Server and Visual Studio.

The asp.net code I am trying to use is:


Me.SqlSelectCommand1.CommandText = "SELECT news_title, news_date, news_type, news_link FROM news WHERE (news_type = 'news') AND (news_date BETWEEN CONVERT(DATETIME, '"" & startdate & ""', 102) AND CONVERT(DATETIME, '"" & enddate & ""', 102))"

....

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim startdate As DateTime
startdate = Request.Form("date_from")

Dim enddate As DateTime
enddate = Request.Form("date_to")

SqlDataAdapter1.Fill(DataSet1)
Repeater1.DataSource = DataSet1
Repeater1.DataBind()

End Sub


With this I am getting the following error:

"Syntax error converting datetime from character string. "

So I am assuming it is something to do with the way I am getting the date from the form as when I hardcode the dates in it works???

Any help would be greatly appreciated, thanx

View 1 Replies View Related

Count Records Between Two Dates

Apr 20, 2004

Hi all,

I've got a quick question.

How would I count the number of records between two dates.

I started with something like this.

SELECT COUNT(*) AS COUNT, dtAdded
FROM tSurveyPerson
WHERE (dtAdded BETWEEN '2004-03-01' AND '2004-04-01')
GROUP BY dtAdded

but as you probably all know this ain't right. I would like to get just the number of records.

Thanks

View 2 Replies View Related

Return Records Between Dates

Feb 15, 2007



Hi,

I need some help with this please.



I have a database table which contains customer orders. I am trying to code my SQL select statement to:

1) Only return records where the record orderdate is within the last 30 days

2) Between two dates, selected from the datepicker control.

With regards to issue 1, I could fill a table with all the records for the account in question and then for each record do a datediff between the records order date and the current date to determine if the number of days is within 30 days. If yes then add this record to a temp table and then set this table as the datasource for the datagridview.

There must be a more efficient way?

With regards to issue 2) ?

View 1 Replies View Related

Insert Records Loop For Dates?

Aug 27, 2012

I have a table with employee references and a startdate.

I want to insert into a new table an entry for each employee for each date since their startdate to today.

Eg

EMPTABLE

empref,startdate

0001,01.01.2012
0002,02.02.2012

What I require is

NEWTABLE

empref, Date
0001,01.01.2012
0001,01.02.2012
0001,01.03.2012
......
0001,08.27.2012
0002,02.02.2012
0002,02.03.2012
......
0002,08.27.2012

View 5 Replies View Related

Update Records Base On Dates?

May 12, 2014

I have a table like this one, with PurchaseID be the primary key.

Code:

PurchaseIDItemIDQtyDatePurchased
1105152010-01-12
210742012-11-30

[Code]...

But I can't figure out how to get the max DatePurchased of the same ItemID.

View 4 Replies View Related

Pulling Unique Records With Max Dates

Mar 5, 2006

I am trying to pull only those records with a maximum upload date for a file upload log.

This table keeps a list of files uploaded by supplierID and will have multiple records from the same supplier but with all different upload dates. Overall there are over 1,000 records for 48 uniqur suppliers.

The field names are:
SupplierID, UploadDate, FeedFileName, RecordCount, FeedFileDate, RecordCount, and FeedLoaded.

So for each distinct SupplierID I'd like to grab the line item based on the max feedfiledate for each one - in other words I am trying to get the latest uploaded file information, how many records were in the file, and when it was uploaded... I've tried multiple group by and max clauses but there is something I am missing...

Thanks Much in advance

View 4 Replies View Related

SELECTing Records That Fall Between Two Dates

May 19, 2008



Hi, I was wondering if anyone can help me write a SELECT statement to return all records (rows) based on whether they fall within two dates. For example, consider this table:




Code Snippet
--DROP TABLE #Records
CREATE TABLE #Records
(RecordID INT PRIMARY KEY NOT NULL,
StartDate DATETIME,
EndDate DATETIME)
INSERT INTO #Records
VALUES
(1, '2008-05-01', '2008-05-12')
INSERT INTO #Records
VALUES
(2, '2008-05-08', '2008-05-12')
INSERT INTO #Records
VALUES
(3, '2008-05-19', '2008-05-22')
INSERT INTO #Records
VALUES
(4, '2008-05-22', '2008-05-23')
INSERT INTO #Records
VALUES
(5, '2008-05-26', '2008-06-01')
INSERT INTO #Records
VALUES
(6, '2008-05-28', '2008-06-01')
SELECT * FROM #Records






I want to return the RecordID for any row which span this week. I've tried the simple approach of using WHERE GETDATE() BETWEEN StartDate AND EndDate but this doesn't produce the desired results. For example, RecordID 4 spans this current week but is not returned (obviously) with this approach.

The idea is to show which events (rows) are coming up this week and next week. Eventually the data will be used to populate an SSRS report.

Hope that makes sense, can anyone help?

Thanks
Matt

View 10 Replies View Related

How To Select All The Dates Of Month Even Though There Are No Records?

Nov 28, 2007



I have one SQL Table with 2 columns as below


Column1: ProductionDate - DateTime - Not NULL
Column2: Quantity - Int - Not NULL

Now There are 2 Records in Table

1-1-2007, 5
1-3-2007, 7


Output of Result should be as below

1-1-2007 5
1-2-2007 0
1-3-2007 7
1-4-2007 0
1-5-2007 0
1-6-2007 0
.
.
.
1-31-2007 0

Means Query should return all the dates of Month with Quantity and if no entry in Table then 0 for Quantity.

How to Do it? Please suggest with Query

View 5 Replies View Related

Problem Using Query To Get Records Between Two Dates

Feb 10, 2008

I´m trying to select records which are between two dates. I use the following statement.


qry = System:tring::Format("SELECT sum(breakfast), sum(colacao), sum(lunch), sum(snacks), sum(dinner) FROM alunos, logtable WHERE alunos.cad_matr=logtable.studentid and alunos.cad_matr="+tbStudentId->Text+" and dateofmeal >=#"+dt->ToString("dd/MM/yyyy 00:00:00" )+"# and dateofmeal <=#"+dt2->ToString("dd/MM/yyyy 00:00:00" )+"#" );




Although the records exists the query does not get these records. If I go to the Query Design and use the same query it works but only if I enter the dates manually (dateofmel >=?).

Can anybody help me to solve thih /

Thanks

View 3 Replies View Related

Selecting Records Between Two Dates (should Work But It Doesn't)

Nov 6, 2006

Hello. I need to create a page with asp 3 and sql server 2000 that lists all the records in a table that match a date criterion, but when doing so I get an error "Error Converting datetime from character string"...
I've tried this versions of the query:


Code:

SELECT (...) CONVERT(DATETIME,PAYMENTS_RECEIVED.PYR_DATE,103), (...)
FROM RESERVES LEFT OUTER JOIN (...)
WHERE (PAYMENTS_RECEIVED.PYR_DATE BETWEEN '20/03/2006' AND '21/03/2006')



and...


Code:

SELECT (...) PAYMENTS_RECEIVED.PYR_DATE, (...)
FROM RESERVES LEFT OUTER JOIN (...)
WHERE (PAYMENTS_RECEIVED.PYR_DATE >= CONVERT(DATETIME,'20/03/2006',103)) AND (PAYMENTS_RECEIVED.PYR_DATE < CONVERT(DATETIME,'21/03/2006',103))



I also tried adding " 00:00:00 a.m." to the dates to be converted in the second piece of code. If I recall correctly, "103" is the convertion code meaning "dd/mm/yyyy". That is, I expect people to type in a date like "27/03/2006" and get the table records from that date.

Weirdest thing of all is that, when using the query builder of a sqlsource control in Visual Studio Web Developer Express 2005 this following query works just fine as I expect:


Code:

SELECT (...) PAYMENTS_RECEIVED.PYR_DATE, (...)
FROM RESERVES LEFT OUTER JOIN (...)
WHERE (PAYMENTS_RECEIVED.PYR_DATE >= CONVERT(DATETIME, '20/03/2006', 103)) AND (PAYMENTS_RECEIVED.PYR_DATE < CONVERT(DATETIME, ' 21 / 03 / 2006 ', 103))



Both the server and the DB are the same in all cases, but in the first two I run the query from a (working of other queries) vbscript asp 3 page.

I know that similar posts exist already (I've searched for this before posting), but I can't fix it, at least not with the usual answer on this one (that seems to be using the convert function as in the first piece of code). Thanks in advance!!!

View 4 Replies View Related

SQL Server 2008 :: Selecting Records Not Between 2 Dates

Jul 22, 2015

I’m trying to extract a list of records that don’t appear between 2 dates. I have 4 tables:

tblCustomers
tblMachines
tblServiceOrders
tblMachinesServiced

tblCustomers contains a CustomerID that is unique to each customer.

tblMachines contains a list of all machines with a MachineID that is unique to each machine. It also contains the CustomerID number.

tblServiceOrders contains a list of each time each customer was serviced. It contains the ServiceDate, CustomerID, and ServiceOrderNo. But it does not have any information on the machines.

tblMachinesServiced contains a list of each machine that was serviced for each service order. It contains the ServiceOrderNo and the MachineID number.

What I want is to be able to extract a list of machines that were not serviced between 2 dates. What I end up getting is a list of machines that were serviced outside of the date range I provide.

For instance, say machine A was serviced in 2013 and 2015 but not in 2014. And say machine B was serviced in all 3 years. When I try to extract my list of machines not serviced in 2014 I end up with a list that contains machine A-2013, A-2015, B-2013 & B-2015. But what I need is just machine A-2014, since that machine wasn’t serviced in 2014.

I’ve tried several different queries but here is an example:

SELECT tblMachines.MachineID,ServiceMachines.ServiceDate
FROM tblMachines
LEFT JOIN
(SELECT MachineID, ServiceDate FROM tblServiceOrders, tblMachinesServiced
WHERE tblServiceOrders.ServiceOrderNo=tblMachinesServiced.ServiceOrderNo
) ServicedMachines
ON tblMachines.MachineID=ServicedMachines.MachineID
WHERE YEAR(ServiceDate) != '2014'

I understand why it returns the records that it does, but I'm not sure how to get what I want, which is a list of machines not serviced in 2014.

View 9 Replies View Related

Selecting Records Between Time Ranges On Dates

May 8, 2008

I'm looking for a way to link records that would be related to an employee that worked during that shift.

we have 2 shifts days and nights going from 6:00AM to 6:00PM

we have records that are written to a table as events happen on equipment on site.

"Equip_Trans"

"Start_time" "Equip_ID" "Shift_date" "Status" "End_Time"
Date-Time, int, Date, varchar(3), Date-time
5/8/2008 4:23:25 AM, 0200, 5/8/2008, M20, 5/8/2008 5:15:34 AM
5/8/2008 2:18:45 AM, 0206, 5/8/2008, M24, 5/8/2008 3:10:03
5/8/2008 5:15:34 AM, 0200, 5/8/2008, M13, 5/8/2008 7:24:36 AM
5/8/2008 3:10:03 AM, 0206, 5/8/2008, M20, Null
5/8/2008 7:24:36 AM, 0200, 5/8/2008, O21, 5/8/2008 7:55:34 AM
5/8/2008 7:55:34 AM, 0200, 5/8/2008, M24, 5/8/2008 8:36:34 AM


I have another transaction table "Operator_Trans"
"Operator" "Date" "Shift"

jane Doe, 5/6/2008, 1
Pete Who, 5/6/2008, 2
Sam What, 5/7/2008, 1
Pete Who, 5/7/2008, 2
john Doe, 5/8/2008, 1
jane Doe, 5/8/2008, 2


and last a third table "Shift"
Shift, Start_Time, End_Time
1, 6:00AM, 6:00PM
2, 6:00PM, 6:00AM

I need out put that will show all Equipment status's that started during the shifts worked by an operator

Pete Who, 5/8/2008 4:23:25 AM, 0200, 5/8/2008, M20, 5/8/2008 5:15:34 AM
Pete Who, 5/8/2008 2:18:45 AM, 0206, 5/8/2008, M24, 5/8/2008 3:10:03 AM
Pete Who, 5/8/2008 5:15:34 AM, 0200, 5/8/2008, M13, 5/8/2008 7:24:36 AM
Pete Who, 5/8/2008 3:10:03 AM, 0206, 5/8/2008, M20, Null
john Doe, 5/8/2008 7:24:36 AM, 0200, 5/8/2008, O21, 5/8/2008 7:55:34 AM
john Doe, 5/8/2008 7:55:34 AM, 0200, 5/8/2008, M24, 5/8/2008 8:36:34 AM

I am not completely sure the direction I should start off with. I have some SQL knowlege but I would still consider myself new.

Thanks

View 1 Replies View Related

SQL Query - Duplicate Records - Different Dates - How To Get Only Latest Information?

Mar 17, 2006

I have a SQL query I need to design to select name and email addressesfor policies that are due and not renewed in a given time period. Theproblem is, the database keeps the information for every renewal inthe history of the policyholder.The information is in 2 tables, policy and customer, which share thecustid data. The polno changes with every renewal Renewals in 2004would be D, 2005 S, and 2006 L. polexpdates for a given customer couldbe 2007-03-21, 2006-03-21, 2005-03-21, and 2004-09-21, with polno of1234 (original policy), 1234D (renewal in 2004), 1234S (renewal in2005), and 1235L (renewed in 2006).The policy is identified in trantype as either 'rwl' for renewal, or'nbs' for new business.The policies would have poleffdates of 2004-03-21 (original 6 monthpolicy) 2004-09-21 (first 6 month renewal) , 2005-03-21 (2nd renewal,1 year), 2006-03-21(3rd renewal, 1 yr).I want ONLY THE LATEST information, and keep getting earlyinformation.My current query structure is:select c.lastname, c.email, p.polno, p.polexpdatefrom policy p, customer cwhere p.polid = c.polidand p.polexpdate between '2006-03-01 and 2006-03-31and p.polno like '1234%s'and p.trantype like 'rwl'and c.email is not nullunionselect c.lastname, c.email, p.polno, p.polexpdatefrom policy p, customer cwhere p.polid = c.polidand p.polexpdate between '2006-03-01 and 2006-03-31and p.polno like '1234%'and p.trantype like 'nbs'and c.email is not nullHow do I make this query give me ONLY the polno 123%, or 123%Sinformation, and not give me the information on policies that ALSOhave 123%L policies, and/ or renewal dates after 2006-03-31?Adding a 'and not polexpdate > 2006-03-31' does not work.I am working with SQL SERVER 2003. Was using SQL Server 7, but foundit was too restrictive, and I had a valid 2003 licence, so I upgraded,and still could not do it (after updating the syntax - things likeusing single quotes instead of double, etc)I keep getting those policies that were due in the stated range andHAVE been renewed as well as those which have not. I need to get onlythose which have NOT been renewed, and I cannot modify the database inany way.*** Free account sponsored by SecureIX.com ****** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com ***

View 24 Replies View Related

Select Records Between Dates - Query Works In VS 2005 But It Doesn't In Asp 3

Nov 9, 2006

Hello. I'm having troubles with a query that (should) return all therecords between two dates. The date field is a datetime type. The db isSQL Server 2000. When I try thisSELECT RESERVES.RES_ID, PAYMENTS_RECEIVED.PYR_ID,PAYMENTS_RECEIVED.PYR_VALUE, PAYMENTS_RECEIVED.PYR_DATE,CUSTOMERS.CUS_NAMEFROM RESERVES LEFT OUTER JOINPAYMENTS_RECEIVED ON RESERVES.RES_ID =PAYMENTS_RECEIVED.RES_ID LEFT OUTER JOINCUSTOMERS ON RESERVES.CUS_ID = CUSTOMERS.CUS_IDWHERE (PAYMENTS_RECEIVED.PYR_DATE >= '2006-03-20 00:00:00') AND(PAYMENTS_RECEIVED.PYR_DATE < '2006-03-27 00:00:00')on a "query builder" in visual studio, I get the results that I want.But when I use exactly the same query on an asp 3 vbscript script, Iget no results (an empty selection).I've done everything imaginable. I wrote the date as iso, ansi, britishformat using convert(,103) (that's how users will enter the dates),i've used cast('20060327' as datetime), etc. But I can't still get itto work. Other querys from the asp pages work ok. Any ideas?thanks a lot in advance

View 1 Replies View Related

T-SQL (SS2K8) :: Historical Data Where Number Of Records Exists Between Two Dates With Different Years

Jul 10, 2015

Ok, I'm looking to get counts on historical data where the number of records exists between two dates with different years. The trick is the that the dates fall in different years. Ex: Give me the number of records that are dated between 0ct 1, 2013 and July 1, 2014.

A previous post of mine was similar where I needed to get records after a specific date. The solution provided for that one was the following. This let me get any records that occured after May 1 per given Fiscal year.

SELECT
MAX(CASE WHEN DateFY = 2010 THEN Yr_Count ELSE 0 END) AS [FY10],
MAX(CASE WHEN DateFY = 2010 THEN May_Count ELSE 0 END) AS [May+10],
MAX(CASE WHEN DateFY = 2011 THEN Yr_Count ELSE 0 END) AS [FY11],
MAX(CASE WHEN DateFY = 2011 THEN May_Count ELSE 0 END) AS [May+11],
MAX(CASE WHEN DateFY = 2012 THEN Yr_Count ELSE 0 END) AS [FY12],

[Code] ....

I basically need to have CASE WHEN MONTH(OccuranceDate) between Oct 1 (beginning year) and July 1 (ending year).

View 4 Replies View Related

SQL Server 2008 :: Calculate Number Of Months Between Dates For Multiple Records?

Oct 7, 2015

I have a challenge and I'm not sure the best route to go. Consider the following dataset.

I have a table of sales. The table has fields for customer number and date of sale. There are 1 - n records for a customer. What I want is a record per customer that has the customer number and the average number of months between purchases. For example, Customer 12345 has made 5 purchases.

CustomerNumber SalesDate
1234 05/15/2010
1234 10/24/2010
1234 02/20/2011
1234 05/02/2012
1234 12/20/2012

What I want to know is the average number of months between the purchases. And do this for each customer.

View 6 Replies View Related

Selecting Records Based On Two Conditions

Oct 25, 2007

Hi! I have a table Tbl1 has to columns:
A          B
_________
Ibm       Me
Sony     Me
Me        Bob
Me        Frank
I'd like to select all rows where B=ME and A=Me Thanks for the help

View 2 Replies View Related

Calculating A Field Value Based On Other Records

May 20, 2008

I have two tables and they have a foreign key relationship.  It will be a 1 to Many realationship. 
Table1- the primary key table has the following columns
ContentID - int identity field
DateAdded- datetime
Table2 - The foreign key table, has the following relevant fields
FK - int foreign key
version - int
When an initial record is added there is a record added to each table.  The ContentID in Table1 will match the FK field in Table2.  Then a user will be able to "edit" the record in Table2, but instead of writing over the record that is already there, a new record will be added to Table2.  I would like to calculate the version field where each time a record is added for the particular ContentID/FK it adds 1 to the last version that was added to that particular ContentID/FK. 
 Does that make sense.  I am trying to implement some type of revision tracking for my CMS that I am building and this is the only way I can come up with because my client is worried that somebody will go in and make incorrect changes to their site and  they want to be able to roll it back to a previous version. 
I would appreciate any ideas.
Thanks,
laura

View 5 Replies View Related

How To Delete Records Based On Time?

Oct 8, 2003

Hello

I want to delete my record after ten days of the Posted date(field)..how do I do it? I'm able to insert date(short date , long time) to the database. I'm using sql server and C#. this is what I have so far.I would appreciate your help..

Thanks!!!<%@ Page Language="C#"%>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat=server>

void Page_Load(Object sender , EventArgs e)
{
SqlConnection conPubs;
string strDelete;
SqlCommand cmdDelete;

conPubs = new SqlConnection( @"Server=localhost;Integrated Security=SSPI;database=Book" );
strDelete = "Delete tblbook Where Posted_Date =???????????";
cmdDelete = new SqlCommand( strDelete, conPubs );
conPubs.Open();
cmdDelete.ExecuteNonQuery();
conPubs.Close();
Response.Write("Records Deleted!");
}
</script>
//

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<!-- Insert content here -->
</form>
</body>
</html>

View 6 Replies View Related

How To Create Set Of Records Based On SELECT

Oct 10, 2014

I have a set of records that will always be the same. A template if you wanna call it that.

"SELECT ID, Field1, Field2, Field3, Field4, Field5, Field6, Field7 FROM TABLE WHERE Field2 = 000"

This returns a 20 record set. The user will click a button and create another set of 20 records, where they can make changes accordingly.

View 8 Replies View Related







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