我正在尝试使用G / L表并在两个其他表之间连接,然后在语句中显示每个G / Ls的最新条目,但我不知道该尝试什么。
SELECT
GLACCOUNT.GLACODE,
GLACCOUNT.GLADESC,
GLACCOUNT.GLATYPE,
GLACCOUNT.GLAACTIVE,
GLENTHDR.GLEHENTDATE,
GLENTTRL.GLETREM,
GLENTHDR.GLEHUSER,
GLENTHDR.GLEHPP
FROM GLACCOUNT
INNER JOIN GLENTTRL
ON GLACCOUNT.GLACODE = GLENTTRL.GLETCODE
INNER JOIN GLENTHDR
ON GLENTTRL.GLETXACT = GLENTHDR.GLEHXACT
现在我想要的是组合GLACCOUNT.GLACODE并只为每个(GLACODE)显示最新的GLENTHDR.GLEHPP条目。做一些研究我认为我可以做一个WHERE声明,但我不知道如何结合。我是否需要对结果进行子查询?很抱歉这里是个菜鸟。我相信这很简单。感谢。
答案 0 :(得分:0)
我不确定您使用的是哪个数据库,但下面的查询语法是标准SQL。我们的想法是按GLENTHDR
查询每个GLETXACT
记录分组的最新日期。然后让外部查询加入它。
SELECT
GLACCOUNT.GLACODE,
GLACCOUNT.GLADESC,
GLACCOUNT.GLATYPE,
GLACCOUNT.GLAACTIVE,
GLENTHDR.GLEHENTDATE,
GLENTTRL.GLETREM,
GLENTHDR.GLEHUSER,
GLENTHDR.GLEHPP
FROM GLACCOUNT
INNER JOIN GLENTTRL
ON GLACCOUNT.GLACODE = GLENTTRL.GLETCODE
INNER JOIN (
SELECT
GLETXACT,
GLEHUSER,
GLEHPP,
MAX(GLEHENDATE) AS GLEHENDATE
FROM GLENTHDR
GROUP BY GLETXACT, GLEHUSER, GLEHPP
) GLENTHDR
ON GLENTTRL.GLETXACT = GLENTHDR.GLEHXACT
答案 1 :(得分:0)
您需要一个子查询来查找每个辅助表的最后一个事务。看看下面最内在的子查询,它并不是那么糟糕。最内部的子查询只获取辅助表的每个GLETCODE的最后一个ID(不确定您的真实姓名)。我称之为MAXmytablename。然后它连接回辅助表以获得最后一行。然后它将GLACCOUNT.GLETCODE连接到最后一行的GLETCODE。
SELECT GLACCOUNT.GLACODE,
GLACCOUNT.GLADESC,
GLACCOUNT.GLATYPE,
GLACCOUNT.GLAACTIVE,
GLENTHDR.GLEHENTDATE,
GLENTTRL.GLETREM,
GLENTHDR.GLEHUSER,
GLENTHDR.GLEHPP
FROM GLACCOUNT
INNER JOIN (SELECT GLENTTRL.GLETCODE,
GLENTTRL.GLETREM
FROM GLENTTRL
JOIN (SELECT MAX(ID) MAXID,
GLETCODE
FROM GLENTTRL
GROUP BY GLETCODE) AS MAXGLENTTRL
ON MAXGLENTTRL.MAXID = GLENTTRL.ID) AS GLENTTRL
ON GLACCOUNT.GLETCODE = GLENTTRL.GLETCODE
INNER JOIN (SELECT GLENTHDR.GLETCODE,
GLENTHDR.GLEHUSER,
GLENTHDR.GLEHPP,
GLENTHDR.GLEHENTDATE
FROM GLENTHDR
JOIN (SELECT MAX(ID) MAXID,
GLETCODE
FROM GLENTHDR
GROUP BY GLETCODE) AS MAXGLENTHDR
ON MAXGLENTHDR.MAXID = GLENTHDR.ID) AS GLENTHDR
ON GLACCOUNT.GLETCODE = GLENTHDR.GLETCODE