【问题标题】:check and compare the count from two tables without relation检查并比较两个没有关系的表的计数
【发布时间】:2021-04-26 06:18:11
【问题描述】:

我有以下表格

表 1:“演示” 列:SSN、销售额、Create_DT、Update_Dt

表 2:“代理” 列:SSN、sales、Agent_Name、Create_Dt、Update_DT

场景 1 和期望的结果集: 如果 Demo 表中的 SSN 计数与 Agent 表中的 SSN 计数匹配,我希望输出为 0 如果计数不匹配,那么我希望结果为 1

场景 2 和所需的结果集: 如果 Demo 表中的销售额总和与 Agent 表中的销售额总和匹配,我希望输出为 0 如果总和不匹配,那么我希望结果为 1

请在此查询部分提供帮助

谢谢

【问题讨论】:

  • 请说明您可能尝试过的任何查询。
  • 轻松为您提供帮助:minimal reproducible example.
  • 用STG as (Select count() as CNT_S from Demo), TGT as (Select count() as cnt_t from Agent) Select STG.CNT_S,TGT.cnt_t,当 STG.CNT_S = TGT.cnt_t 然后 0 否则 1 以匹配来自 STG,TGT 的情况结束 - 它正在工作

标签: sql count google-bigquery sum


【解决方案1】:

您可以分别编写两个查询以在结果查询中进行计数

SELECT (SELECT count(Demo.SSN) as SSN1 from Demo)!=(SELECT count(Agent.SSN) as SSN2 from Agent) AS Result;

基本上,内部查询所做的是检查计数是否相等,如果为真则输出 1,如果为假则输出 0。由于您要求输出 1 是否为假,因此我使用了 '!=' 符号。

您也可以在方案 2 中尝试相同的过程

【讨论】:

    【解决方案2】:

    对于场景 1

    select (Case when (select count(ssn) from Demo)=(select count(ssn) from Agent) then 0 else 1 end) as desired_result
    

    如果你想计算唯一的 ssn 那么:

    select (Case when (select count(distinct ssn) from Demo)=(select count(distinct ssn) from Agent) then 0 else 1 end) as desired_result
    

    对于场景 2:

    select (Case when (select sum(sales) from Demo)=(select sum(sales) from Agent) then 0 else 1 end) as desired_result
    

    【讨论】:

      【解决方案3】:

      我建议使用两组信息进行一个查询:

      select (d.num_ssn <> a.num_ssn) as have_different_ssn_count,
             (d.sales <> a.sales) as have_different_sales
      from (select count(distinct ssn) as num_ssn,
                   coalesce(sum(sales), 0) as sales
            from demo
           ) d cross join
           (select count(distinct ssn) as num_ssn, 
                   coalesce(sum(sales), 0) as sales
            from agent
           ) a;
      

      注意:这将返回布尔值 -- true/false 而不是 1/0。如果你真的想要0/1,那么使用case

      select (case when d.num_ssn <> a.num_ssn then 1 else 0 end) as have_different_ssn_count,
             (case when d.sales <> a.sales then 1 else 0 end) as have_different_sales
      

      如果您不仅对总计数感兴趣,而且对两个表中的代理/销售组合相同,我也不会感到惊讶。如果是这种情况,请提出一个 问题并给出明确的解释。样本数据和期望的结果有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-04
        • 2016-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多