2016-11-18 11 views
1

と一致する列を返す行を比較し、私は(tbl_customer)のテーブルを持つすべてのレコード(POSTGRESQL)

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

その後、私は同じである列を返す、このテーブル内のすべてのレコードを比較するクエリを必要とします例の結果上記のすべてのrecords..forにする必要があります:

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

またはより良い結果が次のようになります場合は...

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

感謝:) hstore延長とplpgsql使用

+1

を? –

+0

@ HanselF。私はまだコードを始めていません。 – john1717

+0

あなたはもっと正確にあなたが望むことができますか?例えば。テーブルの中に明確に1つの別個の値がある場合にのみ、列名(およびその別個の値)を返したいでしょうか?どのようにNULLを処理したいですか? – verbatross

答えて

1

:機能していないか、そのためにどのようなコードをテストしてきたどのようなコード

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 'スキーマパブリックで拡張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の場合にのみ、 "静的コード" –

関連する問題