简体   繁体   English

获取已合并到多个表中的第一个表计数

[英]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.

相关问题 如何用计数值和伪值聚合联合表? - How to aggregate unioned tables with count and dummy values? 根据多个字段比较 MS Access 中的 2 个表,并获得一个新表,其中的值不包含在第一个表中 - Compare 2 tables in MS Access based on multiple fields and get a new table with values which are not contained in the first table 如果第二次发生多次,如何联接表并获得第一个表的总和 - how to join tables and get sum of first table if second has multiple occurences 有没有办法联接由两个表联合在一起的表? - Is there a way to JOIN a table consisting of two tables UNIONed together? 合并两个联合表? - Combine two unioned tables? 联合表上的SQL条件 - SQL condition on unioned tables 计算表没有数据摄取的天数,并保留所有表的列表,一旦数据被摄取,就从列表中删除 - Count number of days table has had no data ingested, and keep list for all tables, remove from list once data has been ingested 联接两张表,根据第二张表中的多个条件统计第一张表 - Join two tables, count the first table based on multiple conditions in the second table SQL 查询:连接两个表,其中第一个表的实体没有,或另一个表中有多个条目 - SQL Query: Joining two tables where entity of the first table has no, or multiple entries in other table 从哪个表中检索了数据 - From Which Table the data has been retrieved
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM