2016-11-18 78 views
1

我有一個表(tbl_customer)比較行並返回

id | name | birthday | address | gender 
------------------------------------------- 
1 | JOSEPH | 19920413 | NEW YORK | M 
2 | JAKE | 19920413 | LONDON | M 
3 | JOHN | 19920413 | GERMANY | M 

然後我需要一個查詢,將比較表格中的所有記錄,然後返回列,與所有的記錄(PostgreSQL系統)匹配列,它是相同的所有records..for上述結果的例子應該是:

birthday | gender 
------------------- 
19920413 | M 
19920413 | M 
19920413 | M 

或好得多,如果結果是這個樣子..

column_name | value 
-------------------------- 
birthday | 19920413 
gender  | M 

謝謝:)

+1

什麼代碼是不能工作或者是什麼代碼,你一直在測試爲? –

+0

@HanselF。我還沒有開始任何代碼.. – john1717

+0

你能更準確地知道你想要什麼嗎?例如。你是否想要返回一個列名(及其不同的值),當且僅當該列在表中只有一個不同的值時?你想如何處理NULL? – verbatross

回答

1

使用hstore延伸和plpgsql

create function foo(out f_name text, out f_value text) returns setof record language plpgsql immutable as $$ 
declare 
    h hstore; 
    r hstore := null; 
    n text[]; 
begin 
    for h in select hstore(t.*) from tbl_customer as t loop 
    if r is null then 
     r := h; 
    else 
     /* -- To ignore NULLs so the null values does not affects to the result 
     select array_agg(key) into n from each(r) where value is null; 
     r := r || coalesce(slice(h, n), ''); 
     select array_agg(key) into n from each(h) where value is null; 
     h := h || coalesce(slice(r, n), ''); 
     */ -- I believe that there is much more elegant solution is possible 
     r := r - akeys(r - h); 
     exit when r = ''; 
    end if; 
    end loop; 
    raise info '%', r; 
    return query select * from each(r); 
end $$; 

select * from foo(); 

INFO: "gender"=>"M", "birthday"=>"19920413" 
╔══════════╤══════════╗ 
║ f_name │ f_value ║ 
╠══════════╪══════════╣ 
║ gender │ M  ║ 
║ birthday │ 19920413 ║ 
╚══════════╧══════════╝ 
+0

感謝您的答案,但我還沒有運行它,因爲我在hstore中出錯。你知道如何在Windows上安裝嗎? – john1717

+1

@ john1717'使用schema public創建擴展hstore;' – Abelisto

+0

這是正確的..謝謝..但你知道我該如何處理null?以防萬一有可以接受null的列? – john1717

-2
select * 
from tbl_customer 
where birthday in (
    select birthday 
    from tbl_customer 
    group by birthday 
    having count(*) > 1 
) 
+0

謝謝你的建議/答案...有沒有一種方法,我不需要在where子句中指出每一列? – john1717

+0

謝謝..我可以知道誰是誰?以及如何與他聯繫? – john1717

+1

向下投票(1)這甚至不太接近問題的答案(2)這不是MySQL。 Postgres具有分析功能。 –

1

靜態代碼解決方案

select  (array ['id','name','birthday','address','gender'])[pos] as column_name 
      ,min(val)             as value 

from  t cross join 
       unnest(array [id::varchar(10),name,birthday::varchar(10),address,gender]) with ordinality u(val,pos) 

group by pos 

having  ( count (distinct val) = 1 
      and count(*) = count (val) 
      ) 
     or count (val) = 0 
+0

這一個也在工作......謝謝:) – john1717

+0

但有沒有辦法,我不會指出每一列..? – john1717

+0

@ john1717,只有動態SQL,因此「靜態代碼」 –