我想在下面的查询中使用with子句为每个位置使用union。我尝试了多种方法,但未能使其发挥作用。然后我想从查询中创建一个视图。
WITH MaxLoadId AS
(
select MAX(t.loadid) AS loadid, p.partitionkey, p.partdesc, p.partname
FROM tdataseg t
INNER JOIN part p ON t.partitionkey = p.partitionkey
WHERE p.partname = 'MEXICO'
GROUP BY p.partitionkey, p.partdesc, p.partname
)
select distinct
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 datat ON mli.loadid = t.loadid
INNER JOIN details a ON mli.loadid = a.process_id
INNER JOIN category c ON t.catkey = c.catkey
INNER JOIN balances r ON t.RULE_ID = r.RULE_ID;
答案 0 :(得分:0)
你的意思是下面的代码示例吗?您可以首先在每个表达式之间使用逗号指定多个公用表表达式,然后编写引用每个CTE的普通联合查询。
CREATE VIEW dbo.MyView AS
WITH MaxLoadId AS
(
select MAX(t.loadid) AS loadid, p.partitionkey, p.partdesc, p.partname
FROM tdataseg t
INNER JOIN part p ON t.partitionkey = p.partitionkey
WHERE p.partname = 'MEXICO'
GROUP BY p.partitionkey, p.partdesc, p.partname
)
,MaxLoadId_Australia AS
(
select MAX(t.loadid) AS loadid, p.partitionkey, p.partdesc, p.partname
FROM tdataseg t
INNER JOIN part p ON t.partitionkey = p.partitionkey
WHERE p.partname = 'Australia'
GROUP BY p.partitionkey, p.partdesc, p.partname
)
select distinct
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 datat ON mli.loadid = t.loadid
INNER JOIN details a ON mli.loadid = a.process_id
INNER JOIN category c ON t.catkey = c.catkey
INNER JOIN balances r ON t.RULE_ID = r.RULE_ID
UNION ALL
select distinct
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_Australia mli
INNER JOIN datat ON mli.loadid = t.loadid
INNER JOIN details a ON mli.loadid = a.process_id
INNER JOIN category c ON t.catkey = c.catkey
INNER JOIN balances r ON t.RULE_ID = r.RULE_ID