【问题标题】:SQL - Find Record count for multiple tables at a time in snowflakeSQL - 在雪花中一次查找多个表的记录计数
【发布时间】:2021-03-14 22:30:21
【问题描述】:

我希望看到计数有 1 次有表,而不是运行每个。

对于 EX:

select COUNT(*) from  "Fact_MASTER ";
select COUNT(*) from  "Dim_MASTER ";
select COUNT(*) from  "Fact2 ";
select COUNT(*) from  "Dim2";   
select COUNT(*) from  "Fact3";
select COUNT(*) from  "Dim3"

我们有什么方法可以编写一个 CTE 来提取临时表中每个的记录计数,如下所示:

【问题讨论】:

    标签: sql count subquery snowflake-cloud-data-platform snowflake-schema


    【解决方案1】:

    你可以使用union all:

    select 'Fact_MASTER', COUNT(*) from  "Fact_MASTER " union all
    select 'Dim_MASTER', COUNT(*) from  "Dim_MASTER " union all
    select 'Fact2', COUNT(*) from  "Fact2 " union all
    select 'Dim2', COUNT(*) from  "Dim2" union all
    select 'Fact3', COUNT(*) from  "Fact3" union all
    select 'Dim3', COUNT(*) from  "Dim3"
    

    【讨论】:

    • 嗨@Gordon Linoff。在图像中,他似乎想要在列中旋转数据
    【解决方案2】:

    您似乎希望将每个计数放在单独的列中。如果是这样,您可以将每个查询转换为单独的子查询,然后select 他们:

    select 
        (select count(*) from "Fact_MASTER") as fact_master,
        (select count(*) from "Dim_MASTER ") as dim_master,
        (select count(*) from "Fact2")       as fact2,
        (select count(*) from "Dim2")        as dim2,
        (select count(*) from "Fact3")       as fact3
        (select count(*) from "Dim3")        as dim3
    

    【讨论】:

      【解决方案3】:

      您是否尝试过简单地运行:

      SHOW TABLES;
      

      如果您想将该信息用于其他用途,您可以跟进以下内容:

      select "rows" as cnt
      from table(result_scan(last_query_id()))
      where "name" in (...);
      

      如果您有一组想要PIVOT 的表列表,您也可以使用result_scan() 函数来透视数据:

      https://docs.snowflake.com/en/sql-reference/constructs/pivot.html

      【讨论】:

        猜你喜欢
        • 2022-11-22
        • 2020-01-11
        • 2018-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 2014-06-26
        相关资源
        最近更新 更多