2015-04-01 92 views
1

我有兩個表Table1Table2用於查找表中新記錄百分比的SQL查詢

這些表中的每一個都有列Column1, Column2

我需要通過Column2查找Table1組中新Column1的百分比。

1)在列1 =計數(DISTINCT存在於表1列1 的,而不是在表2新記錄的計數)。

2)在TableOne

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

我嘗試什麼是

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

而且這不同的列1的計數

select count(distinct column1) from tableone. 

現在如何在單個查詢中進行組合,並按列2進行組合。

回答

0

快速的方法來做到這一點是:

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 

對於由列2分組,你就必須將其添加到查詢。但是需要知道你想要將其分組。

如果您需要表格間的任何交叉引用(1 & 2)它會稍微複雜一些。

+0

用逗號分開的兩個select命令在HIVE中似乎引發錯誤。拋出的錯誤是「無法識別輸入附近'select''count''('in expression specification」。 – 2015-04-01 14:49:12

+0

這只是SQL結構的通用代碼思想。不完全知道HIVE,加上我沒有全部代碼和表格。 – 2015-04-01 16:29:44