简体   繁体   English

SQL查询返回最大记录

[英]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. 标题表每个Transid有1行,其中明细表可以有多行。

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. 这将返回在特定日期(今天之前的2年)之前的那些零件和暂态记录,但是这些零件也具有在过去2年内具有发票日期的暂态记录。

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: 如果有一个包含所有可用Parts表,而您想包括那些从未包含在发票中的零件,则这是另一种解决方案:

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
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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