如果我的答案在其他地方发布,我道歉,但我已经搜索过,但无法找到它。我试图在SQL中完成以下(使用H2): 这是一个有效的查询:
SELECT
t38.patient_id,
t38.id AS t38id,
t38.effective_time_start AS t38ets,
t38.effective_time_end AS t38ete,
t36.id AS t36id,
t36.effective_time_start AS t36ets,
t36.effective_time_end AS t36ete
FROM View1 AS t38
INNER JOIN View2 AS t36
ON t38.patient_id = t36.patient_id
AND t36.effective_time_start < t38.effective_time_start
我需要做的是在max
上设置t36.effective_time_start
,在t38.id
设置一个组,如下所示:
SELECT
t38.patient_id,
t38.id AS t38id,
t38.effective_time_start AS t38ets,
t38.effective_time_end AS t38ete,
t36.id AS t36id,
MAX(t36.effective_time_start) AS t36ets,
t36.effective_time_end AS t36ete
FROM View1 AS t38
INNER JOIN View2 AS t36
ON t38.patient_id = t36.patient_id
AND t36.effective_time_start < t38.effective_time_start
GROUP BY t38.id
这不起作用。
这是我想要完成的事情: 对于每个患者ID,我有一组t38s和t36s。我想要关于它们的所有数据,加在一起,但我只想要在t38之前t36开始的行。我也只想要每个t38id一行,并且该行需要是最近的(最大开始时间)t36,但它不能只是最大值,它必须仍然在t38开始时间之前。
DISTINCT ON
和RANK ON PARTITION
都是我无法尝试的方法,因为它们在H2中不受支持。想法?
答案 0 :(得分:0)
我对您的数据不太熟悉,但是会有以下工作吗? (可能需要一些调整才能达到预期效果)
SELECT t38.patient_id,
t38.id AS t38id,
t38.effective_time_start AS t38ets,
t38.effective_time_end AS t38ete,
t36.id AS t36id,
t36.effective_time_start AS t36ets,
t36.effective_time_end AS t36ete
FROM View1 AS t38
INNER JOIN View2 AS t36
ON t38.patient_id = t36.patient_id
AND t36.effective_time_start < t38.effective_time_start
JOIN (SELECT MAX(View1.effective_time_start) MaxDate,
view1.paitent_id
FROM View1
INNER JOIN View2
ON View1.patient_id = View2.patient_id
WHERE View2.effective_time_start < View1.effective_time_start
GROUP BY View1.paitent_id) MaxDateCalc
ON MaxDateCalc.paitent_id = t38.paitent_id
and MaxDateCalc.MaxDate = t38.effective_time_start
答案 1 :(得分:0)
我不确定这是否有帮助,但在我的测试中,您的第二个查询似乎唯一的错误就是分组依据。在一些基本的临时表中,我得到了每个正确的1行,它是最大值。
SELECT
t38.patient_id,
t38.id AS t38id,
t38.effective_time_start AS t38ets,
t38.effective_time_end AS t38ete,
t36.id AS t36id,
MAX(t36.effective_time_start) AS t36ets,
t36.effective_time_end AS t36ete
FROM View1 AS t38
INNER JOIN View2 AS t36
ON t38.patient_id = t36.patient_id
AND t36.effective_time_start < t38.effective_time_start
GROUP BY t38.patient_id,
t38.id AS t38id,
t38.effective_time_start AS t38ets,
t38.effective_time_end AS t38ete,
t36.id AS t36id,
t36.effective_time_end AS t36ete