SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Show all data only if specific data meets criteria
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

blund
Starting Member

23 Posts

Posted - 03/12/2012 :  16:45:48  Show Profile  Reply with Quote
This will probably help in several areas.
For example, show me the documents if and only if the first one is less then 365 days old, or in other words, I would like to see all invoices for a group of customers only if there are no invoices older than 1 year for those customers


Here is the base code, showing the tables and columns I am using to simply get all the data from 2 joined tables.

SELECT  GemSQL.dbo.Invoice_Header.Customer,
        GemSQL.dbo.Invoice_Header.Document_Date,
        GemSQL.dbo.Invoice_Detail.Amount

FROM   GemSQL.dbo.Invoice_Header INNER JOIN
       GemSQL.dbo.Invoice_Detail ON
       GemSQL.dbo.Invoice_Header.[Document] = 
       GemSQL.dbo.Invoice_Detail.[Document]

ORDER BY GemSQL.dbo.Invoice_Header.Customer


I can filter and show the invoices using ">getdate()-365", but I am not sure how to show them only if the very first one is less then 1 year old.

Thank you

GilaMonster
Flowing Fount of Yak Knowledge

South Africa
4507 Posts

Posted - 03/12/2012 :  18:25:18  Show Profile  Visit GilaMonster's Homepage  Reply with Quote
SELECT  ih.Customer,
        ih.Document_Date,
        id.Amount
FROM   GemSQL.dbo.Invoice_Header ih INNER JOIN GemSQL.dbo.Invoice_Detail id ON ih.[Document] = id.[Document]
       INNER JOIN (SELECT Customer, MIN(DocumentDate) as EarliestInvoice FROM GemSQL.dbo.Invoice_Header GROUP BY Customer) AS Earliest on Earliest.Customer = ih.Customer
WHERE Earliest.EarliestInvoice > DATEADD(yy,-1,getdate())
ORDER BY GemSQL.dbo.Invoice_Header.Customer


--
Gail Shaw
SQL Server MVP
Go to Top of Page

blund
Starting Member

23 Posts

Posted - 03/12/2012 :  18:50:49  Show Profile  Reply with Quote
Great!
Thank you very much!
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.08 seconds. Powered By: Snitz Forums 2000