SQL | Criteria查询子查询中的最大值

时间:2015-07-07 14:34:03

标签: sql-server jpa hibernate-criteria

我需要找出对应于table2中行的行,它为下面的查询提供单行输出。 我将为此查询编写JPA条件查询。 我可以从子查询中获取max(日期),但不能获得table2的确切行(对应于此最大值)。

SELECT table2.ER AS col_0_0_,
       table1.CR AS col_1_0_
FROM table1 table1 CROSS
JOIN table2 table2
WHERE table2.date=
    (SELECT max(table2i.date)
     FROM table3 table3 CROSS
     JOIN table2 table2i
     WHERE table2i.id=table2.id
       AND table2i.FC=?
       AND table2i.TC=?
       AND table2i.TCOB=?
       AND table2i.FCOB=?
       AND table2i.TC=table1.id
       AND table2i.RT=?
       AND table2i.RTOB=?
       AND table3.id=?
       AND table2i.date<=table3.CD)

2 个答案:

答案 0 :(得分:0)

要将您的加入限制为单行,而不是加入日期,请​​加入ID:

WHERE table2.id=(
  SELECT TOP 1 table2i.id
  FROM table2 table2i
  CROSS JOIN table3 
  WHERE ...
  ORDER BY date DESC
)

ORDER BY日期DESC强制它选择具有最高日期值的行,但将其限制为仅一行(前1个)。

答案 1 :(得分:0)

Using below solved the issue :

SELECT table2.ER AS col_0_0_,
       table1.CP AS col_1_0_
FROM CV table1 CROSS
JOIN ER_VIEW table2
WHERE table2.FCI=?
  AND table2.TCI=?
  AND table2.TCOB=?
  AND table2.FCOB=?
  AND table2.TCI=table1.id
  AND table2.RTI=?
  AND table2.RTOB=?
  AND table2.date=
    (SELECT max(table2i.date)
     FROM DATE_VIEW table3 CROSS
     JOIN ER_VIEW table2i
     WHERE table2i.FCI=?
       AND table2i.TCI=?
       AND table2i.TCOB=?
       AND table2i.FCOB=?
       AND table2i.RTI=?
       AND table2i.RTOB=?
       AND table3.id=?
       AND table2i.date<=table3.CD)