如何从一个结果行中的单个表中的多个行中选择数据?

时间:2015-04-26 02:46:16

标签: sql postgresql

如何在单个查询中选择多个条目。

db表结构表示类似电子表格的excel。每个观察都是一本练习册。

Work book 1  
1     2  
3     4  

Work book 2  
5    6  
7    8  

每个db行代表一个单元格,并在单独的工作簿中进行观察。 表定义是:

observation integer 
row_number integer
col_number integer
value integer

然后数据库看起来像这样:

observation row_number  col_number  value  
    1        1             1        1  
    1        1             2        2  
    1        2             1        3  
    1        2             2        4  
    2        1             1        5  
    2        1             2        6  
    2        2             1        7  
    2        2             2        8  

问题是如何创建单个查询:

select observation, value as value1 from database where row_number = 1 and col_number = 2,
select value as value2 from database where row_number = 2 and col_number = 1;

创建:

observation value1  value2  
1             2      3  
2             6      7 

我尝试过连接和子查询。

2 个答案:

答案 0 :(得分:2)

基本答案是自我加入。表名'数据库'非常令人反感:我打电话给它'电子表格'。

 SELECT r1.observation, r1.value AS value1, r2.value AS value2
   FROM spreadsheet AS r1
   JOIN spreadsheet AS r2
     ON r1.observation = r2.observation
  WHERE r1.row_number = 1
    AND r1.col_number = 2
    AND r2.row_number = 2
    AND r2.col_number = 1

还有很多其他方法可以编写相同的查询。其中之一是:

 SELECT r1.observation, r1.value1, r2.value2
   FROM (SELECT observation, value AS value1
           FROM spreadsheet
          WHERE r1.row_number = 1
            AND r1.col_number = 2
        ) AS r1
   JOIN (SELECT observation, value AS value2
           FROM spreadsheet
          WHERE r2.row_number = 2
            AND r2.col_number = 1
        ) AS r2
     ON r1.observation = r2.observation

答案 1 :(得分:1)

Jonathan也有一个很好的答案,但如果您需要从观察中获取两个以上的值,您可能会发现这种方法更好。我认为他的联合应该很快,但我不知道你的桌子有多大。

我要求你在多个地方指定(行,列)对,这是一个小缺点。

select
    observation,
    min(case when row_number = 1 and column_number = 2 then value end) as value1,
    min(case when row_number = 2 and column_number = 1 then value end) as value2
from T
where (row_number = 1 and column_number = 2) or (row_number = 2 and column_number = 1)
group by observation