简体   繁体   中英

SQL query to return max record

I have two tables with the following fields

Order Header
TransID, InvoiceDate

Order Detail
TransID, PartID

I am trying to write a query that will return those parts which have not had an order header entry since a specific date.

The header table has 1 row per transid, where the detail table can have multiple rows.

Here is what I have been trying:

select h.transid,partid, h.invoicedate
from tblaphistdetail d
right outer join tblaphistheader h
on d.transid = h.transid
where partid <> ''
and h.invoicedate <= dateadd(yyyy,-2,getdate())
group by h.transid,partid, invoicedate
order by partid

This returns those parts and transids which are prior to the specific date (2 years prior to today), but the parts also have transids which have an invoicedate within the last 2 years.

Can anyone help me?

Change:

and h.invoicedate <= dateadd(yyyy,-2,getdate())

to:

and h.transid NOT IN (SELECT transid
                      FROM tblaphisheader
                      WHERE invoicedate > dateadd(yyyy,-2,getdate()))

UPDATE:

select h.transid,partid, h.invoicedate
from tblaphistdetail d
inner join tblaphistheader h
on d.transid = h.transid
where partid <> ''
and partid NOT IN (SELECT partid
                   FROM tblaphisdetail d
                   INNER JOIN tblaphistheader h
                   ON d.transid - h.transid
                   WHERE invoicedate > dateadd(yyyy,-2,getdate()))
group by h.transid,partid, invoicedate
order by partid

If you want to include only parts for which orders exist but not since a specific date, you could try the following:

SELECT
  d.PartID,
  MAX(h.InvoiceDate) AS LastOrdered
FROM
  dbo.tblaphistdetail AS d
INNER JOIN
  dbo.tblaphistheader AS h ON d.TransID = h.TransID
GROUP BY
  d.PartID
HAVING
  MAX(h.InvoiceDate) < @SpecificDate
;

If there's a Parts table with all the parts available and you want to include those that have never been included in an invoice, here's another solution:

SELECT
  p.PartID,
  MAX(h.InvoiceDate) AS LastOrdered
FROM
  dbo.tblaphistdetail AS d
INNER JOIN
  dbo.tblaphistheader AS h ON d.TransID = h.TransID
RIGHT JOIN
  dbo.Parts AS p ON d.PartID = p.PartID
GROUP BY
  p.PartID
HAVING
  MAX(h.InvoiceDate) < @SpecificDate
  OR MAX(h.InvoiceDate) IS NULL
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM