2016-02-04 36 views
1

我需要一個查詢/腳本來顯示錶中每列的不同數量的值。我使用它來與傳統報告結合起來,其中每列是由列數的雙向頻率。類似下面:需要SQL查詢/腳本給我一個表中每列的不同計數

select distinct field1,count(*) 
from EBL_CLIENT.EAP_FACT 
where run_id = '205572' 

select distinct field2,count(*) 
from EBL_CLIENT.EAP_FACT 
where run_id = '205572' 

select distinct fieldetc...,count(*) 
from EBL_CLIENT.EAP_FACT 
where run_id = '205572' 
+0

這通常是用'SE LECT列,COUNT(*)FROM表GROUP BY列。 – Kenney

+0

可能很難獲得** all **列的值的計數,因爲如果列的類型爲CLOB,LOB,BLOB,LONG,XML,Object,嵌套表格等,則無法獲得明確的計數。 – krokodilko

+0

是的,我只是想盡量減少我必須運行的查詢。我在SQL方面經驗不足,不知道是否有可運行的腳本,可以爲EAP_FACT表提供每個字段的不同值計數。有117個不同的領域。 – dag06001

回答

0

這將使每個列的結果在單行

select Field1Count = count(distinct field1) 
,Field2Count = count(distinct field2) 
,fieldetcCount = count(fieldetc) 
from EBL_CLIENT.EAP_FACT 
where run_id = '205572' 
+0

'Field1Count = count(distinct field1)'無效SQL(在SQL標準和Oracle中) –

0

我不知道如果這能幫助,因爲它仍然會運行117個查詢,但你不會必須手動創建它們。運行將返回117個選擇語句的查詢。複製它們並運行它們以獲取計數。

SELECT 'SELECT ''' || COLUMN_NAME || ''' AS ColumnName , COUNT(DISTINCT ' 
    || COLUMN_NAME || ') AS Count FROM ' || Table_Schema || '.' || Table_Name 
FROM INFORMATION_SCHEMA.columns 
WHERE TABLE_SCHEMA = 'EBL_CLIENT' 
    AND TABLE_NAME = 'EAP_FACT' 
+0

SQL中的字符串連接運算符是'||'not'+' –

+0

@a_horse_with_no_name對不起,在想SQL服務器 – SQLChao

1

請在下面找到腳本生成的SQL查詢:

declare 
    v_col varchar2(64) := 'run_id'; 
    v_val varchar2(64) := '205572'; 
    v_table varchar2(64) := 'EAP_FACT'; 
    v_schema varchar2(64) := 'EBL_CLIENT'; 
begin 
    dbms_output.put_line('select *'||chr(10)||'from (select '); 
    for i in (select t.COLUMN_NAME, rownum rn 
      from all_tab_columns t 
      where t.TABLE_NAME = upper(v_table) 
       and t.OWNER = upper(v_schema) 
       and t.COLUMN_NAME <> upper(v_col) 
      order by t.COLUMN_ID) 
    loop 
     dbms_output.put_line('   '||case when i.rn=1 then ' ' else ',' end|| 
          'count(distinct '||i.column_name||') '||i.column_name); 
    end loop; 
    dbms_output.put_line('  from '||v_schema||'.'||v_table||' t where t.'||v_col||' = '''||v_val||''')' 
         ||chr(10)||'unpivot'||chr(10)||'(cnt'); 
    for i in (select listagg (t.COLUMN_NAME,',') within group (order by t.COLUMN_ID) lst 
      from all_tab_columns t 
      where t.TABLE_NAME = upper(v_table) 
       and t.OWNER = upper(v_schema) 
       and t.COLUMN_NAME <> upper(v_col)) 
    loop 
     dbms_output.put_line(' '||'for col in ('||i.lst||')'); 
    end loop; 
    dbms_output.put_line(')'||chr(10)||'order by cnt desc'); 
end; 

你會得到一些這樣的查詢:

select * 
from (select 
      count(distinct t.field1) field1 
      ,count(distinct t.field2) field2 
      ,count(distinct t.field3) field3 
     from EBL_CLIENT.EAP_FACT t where t.run_id = '205572') 
unpivot 
(cnt 
    for col in (field1,field2,field3) 
) 
order by cnt desc 

並運行後,此查詢的結果會是這樣:

col  cnt 
field2 5 
field1 3 
field3 1 
相關問題