在所有情况下PostgreSQL左连接横向输出

时间:2019-05-09 01:13:50

标签: sql postgresql lateral-join

CREATE TABLE public.temp (
    a text COLLATE pg_catalog."default",
    b text COLLATE pg_catalog."default",
    c text COLLATE pg_catalog."default",
    d text COLLATE pg_catalog."default",
    e numeric,
    pkey bigint NOT NULL,
    CONSTRAINT pkey_temp PRIMARY KEY (pkey) )

INSERT INTO public.temp(a, b, c, d, e, pkey)    VALUES
  ('xwlnormingoohlzr','some_value','tebwdlajnzypccgk','nnakygtgpvqxuayg',3276,1),
  ('bnlmykbfdexbrcwj','some_value','zxjlszfazsxpllcp','onlaqqddbsxnogyh',3360,2),
  ('hvjvlsyacstdlvog','some_value','xsznhgrjzhlxvspt','vosoulnvdxbfffer',62,3),
  ('zmgriuziltpbwfys','some_value','nzgnseflbvxcdqev','jefyxrdowtnwznve',1833,4),
  ('ziwhqxbcmbwjduji','some_value','gjiazbxnvkccusxe','wlgmphvqvapvflzi',3936,5),
  ('ldojloaothuwhsky','some_value','onpgbjkjwrjvdisw','ajpmkoshzcvqdsxp',3416,6),
  ('edtgbaqmpvfxqadz','other_value','ostuffegobykyiaf','gommhuppohcypppr',2754,7),
  ('vometxuiataxjdrd','other_value','zvwcularbgyiyrar','hdnamfmjkicgufxk',462,8),
  ('cqbpxyyiklhdvxcd','other_value','qrlvjmkijqohuvnb','hphrmykukcaoqmjy',63,9),
  ('mqwwnemddwynulwy','other_value','plbgdjniyqkzwxwm','waszvkkpinnjofet',59,10),
  ('zehtxhonbrfiiksw','other_value','oaowphudhtaupisp','ezgwzyiolgtehpou',920,11),
  ('ylhzfkyyxvdkftdk','other_value','kknyczaiihxacqjd','tzafbxojawhznmir',2528,12),
  ('dhlnmexaovbivudl','other_value','xbwqogpxaqssqjee','qecclksfpnbtugli',224,13);

我要重复一些符合以下条件的行:

select
    b,
    the_value
from public.temp
    left join lateral 
        unnest(array[-e,e]) as the_value
        on b = 'some_value'

对于b = 'some_value',我想用一个输出e和另一个-e复制行。对于b =“ other_value”,想要输出e

null不是b时,上面的查询将给出'some_value'。我了解这是预期的行为,但是在所有情况下如何输出某些内容?

目前我知道了:

"some_value"    "-3276"
"some_value"    "3276"
"some_value"    "-3360"
"some_value"    "3360"
"some_value"    "-62"
"some_value"    "62"
"some_value"    "-1833"
"some_value"    "1833"
"some_value"    "-3936"
"some_value"    "3936"
"some_value"    "-3416"
"some_value"    "3416"
"other_value"   
"other_value"   
"other_value"   
"other_value"   
"other_value"   
"other_value"   
"other_value"   

我想看看:

"some_value"    "-3276"
"some_value"    "3276"
"some_value"    "-3360"
"some_value"    "3360"
"some_value"    "-62"
"some_value"    "62"
"some_value"    "-1833"
"some_value"    "1833"
"some_value"    "-3936"
"some_value"    "3936"
"some_value"    "-3416"
"some_value"    "3416"
"other_value"   "2754"
"other_value"   "462"
"other_value"   "63"
"other_value"   "59"
"other_value"   "920"
"other_value"   "2528"
"other_value"   "224"

1 个答案:

答案 0 :(得分:0)

您可以简单地做到这一点:

  select b,unnest(CASE WHEN b='some_value' then array[-e,e] else array[e] end)  from public.temp

这将返回预期的结果