0

我在 postgresql-9.1.x 数据库中有一个表,定义如下:

# \d cms
                                      Table "public.cms"
   Column    |            Type             |                    Modifiers                     
-------------+-----------------------------+--------------------------------------------------
 id          | integer                     | not null default nextval('cms_id_seq'::regclass)
 last_update | timestamp without time zone | not null default now()
 system      | text                        | not null
 owner       | text                        | not null
 action      | text                        | not null
 notes       | text

以下是表中数据的示例:

 id  |        last_update         |        system        |   owner   |               action                | 
     notes
 ----+----------------------------+----------------------+-----------+-------------------------------------    +-
----------------
 584 | 2012-05-04 14:20:53.487282 | linux32-test5   | rfell     | replaced MoBo/CPU                   | 
  34 | 2011-03-21 17:37:44.301984 | linux-gputest13 | apeyrovan | System deployed with production GPU | 
 636 | 2012-05-23 12:51:39.313209 | mac64-cvs11     | kbhatt    | replaced HD                         | 
 211 | 2011-09-12 16:58:16.166901 | linux64-test12  | rfell     | HD swap                             | 
drive too small

而忽略了它们之间的关联。所以是这样的:

 system          |    owner
-----------------+------------------
 linux32-test5   |   apeyrovan
 linux-gputest13 |   kbhatt 
 linux64-test12  |   rfell
 mac64-cvs11     |

我能弄清楚获取这些数据的唯一方法是使用两个单独的 SQL 查询:SELECT system FROM cms GROUP BY system;从 cms GROUP BY 所有者中选择所有者;

4

1 回答 1

2

我绝不会问你为什么要做这样的事情。以下查询通过使用 row_number() 函数对计算列进行连接来完成此操作:

select ts.system, town.owner
from (select system, row_number() over (order by system) as seqnum
      from (select distinct system
            from t
           ) ts
     ) ts full outer join
     (select owner, row_number() over (order by owner) as seqnum
      from (select distinct owner
            from t
           ) town
     ) town
     on ts.seqnum = town.seqnum

全外连接确保两个列表中较长的一个完整返回。

于 2012-06-19T18:58:56.497 回答