从两个不同的select语句中获取两行

时间:2016-05-18 11:47:48

标签: sql postgresql postgresql-9.3

我有一张如下表: 表-A

  k | id | results 
--------------------
  a | 1  | mango
  b | 1  | orange
  c | 2  | apple
  d | 2  | banana
  a | 2  | mango

我有两个选择语句,结果如下:

首先选择

select k, id, results from 
table_a where id = 1

结果:

  k | id | results 
--------------------
  a | 1  | mango
  b | 1  | orange

第二次选择

select k, id, results from 
table_a where id = 2

结果:

  k | id | results 
--------------------
  c | 2  | apple
  d | 2  | banana
  a | 2  | mango

如何获得如下结果:

  k | id |  abc  | xyz
------------------------
  a | 1  | mango | mango
  b | 1  | orange| xx
  c | 2  | xx    | apple
  d | 2  | xx    | banana

感谢Gorgon,Praveen。我得到了两种方式的结果。

我还有另一张表格如下:

表-B

  k | 1  | 2 
--------------------
  a |    | 
  b |    | 
  c |    | 
  d |    | 

当我尝试使用以下查询更新table_b时:

update table_b set 
abc = x.abc, xyz = x.xyz from (
select k, id, result as abc, 'xx' as xyz 
from table_a
where id = 1
union all
select k, id, 'xx' as abc, result as xyz
from table_a
where id = 2 ) x
where table_b.k = x.k

我得到的结果如下:

表-B

  k |  1    | 2 
--------------------
  a | xx    | mango
  b | orange| xx
  c | xx    | apple
  d | xx    | banana

我怎样才能得到以下结果 表-B

  k |  1    | 2 
--------------------
  a | mango | mango
  b | orange| xx
  c | xx    | apple
  d | xx    | banana

谢谢,

2 个答案:

答案 0 :(得分:3)

一种方法使用union all

select k, id, results as abc, 'xx' as xyz 
from table_a
where id = 1
union all
select k, id, 'xx' as abc, results as xyz
from table_a
where id = 2;

另一个只使用case

select i, id,
       (case when id = 1 then results else 'xx' end) as abc,
       (case when id = 2 then results else 'xx' end) as xyz
from table_a
where id in (1, 2);

答案 1 :(得分:1)

请检查使用CASE的方法。

DECLARE @table TABLE
    (k CHAR (2),id INT,results VARCHAR(10))
INSERT INTO @table
    (k,id,results)
VALUES
    ('a',1,'mango'),('b',1,'orange'),('c',2,'apple'),('d',2,'banana'),('a',2,'mango')

SELECT 
    k, id,
   (CASE WHEN id = 1 THEN results ELSE 'xx' END) AS abc,
   (CASE WHEN id = 2 THEN results ELSE 'xx' END) AS xyz
FROM
    @table 

请试试下面的代码

 DECLARE @table_b TABLE
    (k CHAR (2),[1] VARCHAR(10),[2] VARCHAR(10))

 INSERT INTO @table_b
    (k)
 VALUES
    ('a'),('b'),('c'),('d'),('a')

 DECLARE @table TABLE
    (k CHAR (2),id INT,results VARCHAR(10))
 INSERT INTO @table
    (k,id,results)
 VALUES
    ('a',1,'mango'),('b',1,'orange'),('c',2,'apple'),('d',2,'banana'),('a',2,'mango')

 SELECT 
    k, id,
   (CASE WHEN id = 1 THEN results ELSE 'xx' END) AS abc,
   (CASE WHEN id = 2 THEN results ELSE 'xx' END) AS xyz
 FROM
    @table 


 UPDATE
   @table_b 
 set 
  [1] = x.abc, [2] = x.xyz from 
   (
     SELECT
       k, id, results as abc, 'xx' as xyz 
     from 
       @table
     where id = 1
     union all
     select 
       k, id, 'xx' as abc, results as xyz
     from 
       @table
     where id = 2 ) x

我相信这是您正在寻找的预期输出。