我现在需要通过多个连接按位置检索最新的loadid。 例如,ibiza的最新装载量为692,有2条记录。下面的查询检索该位置的所有loadid,而不仅仅是最大值。如何通过以下查询中的max(loadid)按位置恢复最新记录:
select
MAX(t.loadid) AS loadid,
a.process_id,
p.partitionkey,
-- t.partitionkey,
p.partdesc,
p.partname,
c.catname,
r.rule_name,
r.file_path,
a.execution_start_time,
a.execution_end_time,
a.records_processed
-- a.status,
-- a.last_updated_by as processed_by,
-- a.last_update_date
FROM
data t
INNER JOIN part p
ON t.partitionkey = p.partitionkey
INNER JOIN process a
ON t.loadid = a.process_id
INNER JOIN categ c
ON t.catkey = c.catkey
INNER JOIN balance r
ON t.RULE_ID = r.RULE_ID
WHERE
p.partname = 'ibiza'
GROUP BY
t.loadid,
a.process_id,
p.partitionkey,
t.partitionkey,
p.partdesc,
p.partname,
c.catname,
r.rule_name,
r.file_path,
a.execution_start_time,
a.execution_end_time,
a.records_processed;
答案 0 :(得分:-1)
您可以使用CTE:
;WITH MaxLoadId AS
(
select MAX(t.loadid) AS loadid, p.partitionkey, p.partdesc, p.partname
FROM data t
INNER JOIN part p ON t.partitionkey = p.partitionkey
WHERE p.partname = 'ibiza'
GROUP BY p.partitionkey, p.partdesc, p.partname
)
select
mli.loadid AS loadid,
a.process_id,
mli.partitionkey,
-- t.partitionkey,
mli.partdesc,
mli.partname,
c.catname,
r.rule_name,
r.file_path,
a.execution_start_time,
a.execution_end_time,
a.records_processed
-- a.status,
-- a.last_updated_by as processed_by,
-- a.last_update_date
FROM MaxLoadId mli
INNER JOIN data t ON mli.loadid = t.loadid
INNER JOIN process a ON mli.loadid = a.process_id
INNER JOIN categ c ON t.catkey = c.catkey
INNER JOIN balance r ON t.RULE_ID = r.RULE_ID