プロが教える店舗&オフィスのセキュリティ対策術

postgreSQL7.3で以下のようなデータの並び替えを実現したいと思っています。

下記のようなデータを・・・
no | recno | name
----+-------+------
1 | 1 | a
1 | 1 | b
1 | 2 | c
1 | 4 | a
2 | 3 | a
2 | 3 | c
2 | 3 | b
3 | 5 | b
4 | 6 | a

下記のような並びにSQLで取得することは可能でしょうか。
no | recno | name1 | name2 | name3
----+-------+------+------+------
1 | 1 | a | b |
1 | 2 | c | |
1 | 4 | a | |
2 | 3 | a | b | c
3 | 5 | b | |
4 | 6 | a | |

noとrecnoのグループごとにnameを横に並べていきたいのですが、
可能なのでしょうか。
できれば、nameは個々のカラムに出力したいのですが、
配列のように1つのカラム内にカンマ区切りでの出力でも構いません。
上記のような表示が可能であれば、SQL文もご教授いただけますと幸いです。

宜しくお願いいたします。

A 回答 (4件)

ちょっとインチキですけど、こんなのはどうでしょうか。


select no, recno, (case when s=1 then 'a'
when s=2 then 'b'
when s=3 then 'a,b'
when s=4 then 'c'
when s=5 then 'a,c'
when s=6 then 'b,c'
when s=7 then 'a,b,c'
else '' end ) as names
from
(select no, recno, sum(case when name = 'a' then 1
when name = 'b' then 2
when name = 'c' then 4
else 0 end) as s
from ex5 group by no,recno order by no,recno) as b;
いちおう動きます(笑)
no | recno | names
----+-------+-------
1 | 1 | a,b
1 | 2 | c
1 | 4 | a
2 | 3 | a,b,c
3 | 5 | b
4 | 6 | a
(6 rows)
    • good
    • 0

質問の趣旨からは外れますが、Accessを入れているなら、


掲題のテーブルをAccessへリンクし、クロス集計クエリを
使うと、お望みの結果が得られます。
    • good
    • 0

postgresqlは専門外なのですが、こんな感じで処理できないですかね。



select
no,
recno,
max(case when r=1 thwn name else null end) as name1,
max(case when r=2 thwn name else null end) as name2,
max(case when r=3 thwn name else null end) as name3
from
(
select
no,
recno,
name,
(select count(*) from x x2 where x2.no=x1.no and x2.recno=x1.renco and x2.name<=x1.name) as r
from x x1
)
group by no,recno
    • good
    • 0

PostgreSQLのカテゴリの中で、この質問の5個下の質問&回答が参考になるのでは?



http://oshiete1.goo.ne.jp/qa4373232.html

この回答への補足

ご回答ありがとうございます。

ARRAY関数はPostgreSQL7.4からの機能でして、
当方が使用しているPostgreSQL7.3の環境で使用することができませんでした。

他に方法をご存知でしたら、ご教授いただけますと幸いです。

補足日時:2008/10/27 22:39
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!