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

私がやりたいのは、システム列と所有者列から一意の/異なる値のみを返すSQLクエリを作成することです(一方の列の結果の値の数がもう一方の列の結果より少ない場合はNULLを入力します)。それらの間の関連付けを無視します。だからこのようなもの:

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

このデータを取得するために私が理解できる唯一の方法は、2つの別々のSQLクエリを使用することです。SELECTsystem FROM cms GROUP BY system; 所有者をcmsGROUPBY所有者から選択します。

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

完全な外部結合により、2つのリストのうち長い方が完全に返されます。

于 2012-06-19T18:58:56.497 に答える