我通过左边的表格从两个表中获取数据,我必须根据其最大值得到一个特定的记录,这是我的查询
select t1.Id,t2.LastModifiedDate,t2.TypeId
from Table1 t1
Left join Table2 t2
on t1.Id=t2.Id and (t2.Disabled=0 and t2.TypeId not in (1,3,5))
where
t2.TypeId =8
这是我的表格结构
t1 ==> Id Name Age
t2 ==> TransactionId TypeId LastModifiedDate Disabled Id
我必须在Where子句
中应用这样的条件t2.TypeId =8 and (t2.TransactionId=Max(TransactionId) and t2.Disabled=1)
如何获取特定typeId的Maximum TransactionId? 即,仅当其typeId为8且禁用= 1
时,才传递最大TransactionId答案 0 :(得分:1)
您可以使用子查询来获取特定TypeID的最大transactionID。
SELECT t1.Id, LastModifiedDate, TypeID
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.Id=t2.Id
WHERE (t2.Disabled=0 AND t2.TypeID NOT IN (1,3,5))
AND t2.TypeId=8
AND t2.TransactionId=
(SELECT MAX(TransactionID) FROM Table2 t3 WHERE t3.TypeID=t2.TypeID)
最后一行中的子查询使用Table2并为其提供一个新别名(" t3"),因此您可以为其指定一个条件,该条件引用来自" t2"的TypeID。在主查询中。 我可能没有完全理解你在这里尝试做什么,但重点是你可能想要的东西可以用子查询完成。
如果您想要的只是特定帐户的最新交易,您可以通过简单地选择交易,ORDER BY transactionID DESCending来简化这一过程,并且只需获取第一个结果(即{{ 1}}或LIMIT 1
取决于DBMS。)