Okay, here is what I got, apologies in advance if something is wrong... I did the best I could. I'm not too sure about the primary key portion.
--===== If the test table already exists, drop it
IF OBJECT_ID('TempDB..Deliveries','U') IS NOT NULL
DROP TABLE Deliveries
--===== Create the test table with
CREATE TABLE Deliveries
(
ID INT PRIMARY KEY,
Part VARCHAR(250),
PartDescription VARCHAR(250),
ReceiptDate TIMESTAMP(6),
TimeBetween INT
)
--===== Setup any special required conditions especially where dates are concerned
SET DATEFORMAT DMY
--===== All Inserts into the IDENTITY column
SET IDENTITY_INSERT Deliveries ON
--===== Insert the test data into the test table
INSERT INTO Deliveries (ID, Part, PartDescription, ReceiptDate, TimeBetween)
SELECT '1', 'A','Nut','5/20/2014 12:00AM',-4 UNION ALL
SELECT '2', 'A','Nut','4/20/2014 12:00AM',-3 UNION ALL
SELECT '3', 'A','Nut','9/20/2013 12:00AM',-2 UNION ALL
SELECT '4', 'A','Nut','8/20/2013 12:00AM',-1 UNION ALL
SELECT '5', 'B','Bolt','8/20/2013 12:00AM', 0 UNION ALL
SELECT '6', 'B','Bolt','7/20/2013 12:00AM', 4 UNION ALL
SELECT '7', 'B','Bolt','1/20/2013 12:00AM', 15 UNION ALL
SELECT '8', 'B','Bolt','6/20/2013 12:00AM', 6 UNION ALL
SELECT '9', 'C','Rod','4/20/2014 12:00AM', 7 UNION ALL
SELECT '10', 'C','Rod','11/20/2013 12:00AM', 8 UNION ALL
SELECT '11', 'C','Rod','5/20/2013 12:00AM', -6 UNION ALL
SELECT '12', 'C','Rod','4/20/2014 12:00AM', 5
--===== Set the identity insert back to normal
SET IDENTITY_INSERT Deliveries OFF
For results, I want the query to select the most recent of each part and each part within the past 6 months of that respective most recent part. So, for the data above, this would be returned:
'1', 'A','Nut','5/20/2014 12:00AM',-4
'2', 'A','Nut','4/20/2014 12:00AM',-3
'5', 'B','Bolt','8/20/2013 12:00AM', 0
'6', 'B','Bolt','7/20/2013 12:00AM', 4
'8', 'B','Bolt','6/20/2013 12:00AM', 6
'9', 'C','Rod','4/20/2014 12:00AM', 7
'10', 'C','Rod','11/20/2013 12:00AM', 8
Thanks in advance. I'm sure that there is a simple solution, I am just new to SQL and haven't been able to find an efficient way to do it. Let me know if more information is required. Cheers.