【问题标题】:SQL query for finding percentage of new records in a table用于查找表中新记录百分比的 SQL 查询
【发布时间】:2015-04-01 05:59:31
【问题描述】:

我有两张桌子Table1Table2

这些表中的每一个都有列Column1, Column2

我需要按 Column2 查找 Table1 组中新 Column1 的百分比。

1) Column1 中的新记录计数 = (不同 Column1 的计数 存在于表 1 中,而不存在于表 2 中)。

2) TableOne 中不同 Column1 的计数

百分比 = (1 / 2) * 100。

我尝试的是

 select count(distinct column1) 
    from TableOne left outer join TableTwo on   
                  (tableone.column1=tabletwo.column2) 
    where TableTwo.column1 is null.

还有这个:

select count(distinct column1) from tableone.

现在如何将两者结合在一个查询中并按列分组。

【问题讨论】:

    标签: sql database hiveql


    【解决方案1】:

    快速的方法是:

    select ((countA/countB)*100) as Percentage (
             select count(distinct column1) as countA, 
                    (select count(distinct column1) from tableone) as countB
                from TableOne left outer join TableTwo on   
                              (tableone.column1=tabletwo.column2) 
                where TableTwo.column1 is null) as X
    from X
    

    要按 column2 分组,您只需将其添加到查询中。但需要知道要按哪一列进行分组。

    如果您需要在表(1 和 2)之间进行任何交叉引用,那就有点复杂了。

    【讨论】:

    • 有两个用逗号分隔的选择命令会在 HIVE 中引发错误。抛出的错误是“无法识别'select''count''('在表达式规范中的输入”。
    • 这只是SQL的通用代码结构思想。不知道在 HIVE 中的具体情况,而且我没有你所有的代码和表格。
    【解决方案2】:
    DECLARE @COUNT1 INT
    DECLARE @COUNT2 INT
    
    SELECT @COUNT1 = COUNT(*) FROM  comparetable
    SELECT @COUNT2 = COUNT(*) FROM  comparetable WHERE Description IS NOT NULL
    
    
    SELECT CAST(CAST(@COUNT2 AS DECIMAL(10,2) )/CAST(@COUNT1 AS DECIMAL(10,2)) AS DECIMAL(10,2)) AS PERCENTAGE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2021-11-12
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      相关资源
      最近更新 更多