这是交易。我有一个存储分配的表 - 一个文档分配给用户。在不同的时间,文档被重新分配给另一个用户,但所有分配都存储在分配表中以用于审计目的。合理?像这样......
id documentID userID dateAssigned
-- ---------- ------ ------------
6 32 87 3/4/2013
7 83 87 2/3/2013
8 32 56 5/6/2013
9 12 56 1/2/2013
我需要显示当前分配给给定用户的文档列表。在上面的例子中,用户56分配了两个文档(文档32和12),用户87有一个(文档83),因为文档32随后被分配给另一个用户。我还在吗?
我想要做的是为任何指定的文件(不随后重新分配)返回给定用户的任何记录。因此,如果我查询用户56,我会得到记录#8和#9,如果我查询用户87,我会得到记录#7。这就是我想要做的。
我可以使用以下内容轻松获取每个文档的最新作业列表:
SELECT a.id AS id, a.documentID AS documentID, a.userID AS userID, MAX(sa.dateAssigned) AS dateAssigned FROM DocumentAssignments a GROUP BY documentID
那会回来......
id documentID userID dateAssigned
-- ---------- ------ ------------
7 83 87 2/3/2013
8 32 56 5/6/2013
9 12 56 1/2/2013
但是,当然,如果我只是为此添加一个WHERE子句,我就不会得到我真正想要的东西。例如,如果我使用:
SELECT a.id AS id, a.documentID AS documentID, a.userID AS userID, MAX(sa.dateAssigned) AS dateAssigned FROM DocumentAssignments a WHERE userID=87 GROUP BY documentID
......这会回来......
id documentID userID dateAssigned
-- ---------- ------ ------------
6 32 87 3/4/2013
7 83 87 2/3/2013
...这不好,因为记录#6不是文档32的最新分配记录。
所以,我想做的就是......
SELECT b.id AS id, b.documentID AS documentID, b.userID AS userID, b.dateAssigned AS dateAssigned FROM DocumentAssignments b WHERE id IN (SELECT a.id AS id, MAX(sa.dateAssigned) AS dateAssigned FROM DocumentAssignments a GROUP BY documentID) AND b.userID=87
这几乎是完美的,除了当然,IN子句不起作用,因为它包含两列(id和MAX(dateAssigned))。
了解困境?我试图找出一种方法来使用聚合MAX()函数来限定分组函数,但是它不会出现在结果记录集中。那样可以解决问题。必须有一个优雅的解决方案,但我找不到它。
非常感谢任何帮助。
干杯,
-Foswick
答案 0 :(得分:0)
1)您可以返回所有记录,例如在第一个HQL中,然后在Java中过滤。
2)其他方式,是在同一子查询中过滤ID和用户:
SELECT b.id AS id, b.documentID AS documentID,
b.userID AS userID, b.dateAssigned AS dateAssigned
FROM DocumentAssignments b
WHERE (b.id, b.userID) IN (SELECT a.id AS id, a.userID AS userID,
MAX(sa.dateAssigned) AS dateAssigned
FROM DocumentAssignments a
GROUP BY documentID)
AND b.userID=87
查看以下示例: http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/queryhql.html#queryhql-tuple
3)如果方式2不起作用,请尝试过滤查询,添加用户与分配的最新文档相同的条件,如下所示:
SELECT b.id AS id, b.documentID AS documentID,
b.userID AS userID, b.dateAssigned AS dateAssigned
FROM DocumentAssignments b
WHERE id IN (SELECT a.id AS id, MAX(sa.dateAssigned) AS dateAssigned
FROM DocumentAssignments a
GROUP BY documentID)
AND b.userID=87
AND b.userID IN (SELECT a.userID AS userID, MAX(sa.dateAssigned) AS dateAssigned
FROM DocumentAssignments a
GROUP BY documentID)