这是我想要的伪代码。 我需要在下面的陈述中统计拳头联盟。
SELECT *
FROM Table1
UNION
SELECT Cats.Id + (SELECT COUNT(*) FROM Fist_Union_Result),
Cats.Name
FROM Table2
有什么想法吗?
答案 0 :(得分:1)
假设第一部分是复杂查询,您可以使用with
子句来对其进行别名。这允许您在两个地方使用它,联盟的顶部和您计算的地方:
; with FirstPart as
(
select *
from Table1
)
select *
from FirstPart
union all
select cats.Id - cnt.cnt
, cats.Name
from Table2 cats
cross join
(
select count(*) as cnt
from FistPart
) as cnt
如果您只想要一个唯一ID,可以将union
放在子查询中,只需标记行1..N:
select row_number() over (order by Name) as Id
, Name
from (
select Name
from Table1
union all
select Name
from Table2
) as SubQueryAlias
答案 1 :(得分:0)
这样的事情:
with first_union_result as (
select col1,
col2
from table1
), count_from_first as (
select count(*) as first_count
from first_union_result
)
select col1,
col2
from first_union_result
union all
select cats.id + cnt.first_count,
cats.name
from cats
cross join count_from_first as cnt;
如果您尝试在整体结果中获得一些唯一ID或类似内容,最好使用row_number()
为所有行生成该ID。