[英]Get first table count which has been unioned into multiple tables
Here is a pseudo code what I want. 这是我想要的伪代码。 I need to get count of fist union in following statement.
在下面的陈述中,我需要计算拳头工会的数目。
SELECT *
FROM Table1
UNION
SELECT Cats.Id + (SELECT COUNT(*) FROM Fist_Union_Result),
Cats.Name
FROM Table2
Any idea ? 任何想法 ?
Assuming that the first part is a complex query, you could use the with
clause to alias it. 假设第一部分是一个复杂的查询,则可以使用
with
子句对其进行别名。 That allows you to use it in two places, the top part of the union and the place where you count: 这样一来,您就可以在两个地方使用它,即工会的顶部和您要数的地方:
; 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
If you just want a unique ID, you could place the union
in a subquery and just label the rows 1..N: 如果只需要一个唯一的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
Something like this: 像这样:
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;
If you are trying to get some unique id or something similar into the overall result, you might be better off using row_number()
to generate that for all rows. 如果您试图在整体结果中获得一些唯一的ID或类似的名称,则最好使用
row_number()
为所有行生成该ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.