我在编写多级ms访问子查询时需要帮助

时间:2019-07-14 15:09:54

标签: ms-access subquery

我很难集中精力进行多级查询/子查询。简而言之,我创建了一个名为REGISTER的表,其中包含3个字段:TransactionId(PK),TransDate(DateTime),Amount(Currency)。我需要一个查询来检索TransactionId,其中TransDate是Max,Amount是Min合格记录。例如,如果合格记录的最大值返回5个具有今天的日期的记录(不包括任何将来的日期),我想知道返回的5个记录中最低金额的TransactionId。

我想通过两个单独的查询来完成这项任务,但是我敢肯定它可以通过一个查询来完成。

查询1(qryFlag):

SELECT REGISTER.TransDate, REGISTER.*
FROM REGISTER
WHERE (((REGISTER.TransDate)=(
  SELECT Max(t2.Transdate) from REGISTER t2 
  where Transdate <= Date())));

查询2:

SELECT REGISTER.TransactionId
FROM qryFlag INNER JOIN REGISTER ON qryFlag.TransactionId = REGISTER.TransactionId
WHERE (((qryFlag.Amount)=(SELECT Min(t2.Amount) from qryFlag t2)));

2 个答案:

答案 0 :(得分:1)

尝试:

SELECT TOP 1 VTID.TransactionID
FROM (
SELECT TransactionID, Amount
FROM Register
WHERE TransDate = (SELECT Max(R.TransDate) FROM Register as R WHERE R.TransDate <= Date())
) as VTID
ORDER BY VTID.Amount

HTH

戴尔

答案 1 :(得分:0)

您需要GROUP BY TransDate来获取最低金额,然后加入表格:

SELECT r.* 
FROM REGISTER AS r INNER JOIN ( 
  SELECT TransDate, MIN(Amount) AS MinAmount 
  FROM REGISTER
  WHERE TransDate = (SELECT Max(Transdate) FROM REGISTER WHERE Transdate <= Date())
  GROUP BY TransDate
) AS g on g.TransDate = r.TransDate AND g.MinAmount = r.Amount