2017-06-26 13 views
1

ここで私が解決しようとしている宿題の問題です:SQL/postgresqlを使用してカスタムフレーズ+計算を印刷するにはどうすればよいですか?

Can you have the output be 'Ron Weasley has 2 pets.'? (You need to concatenate strings). 

私はペットの数を引いためのSQLを知っている(2)である:

select count(name) from pets where owner='Ron Weasley'; 

しかし、どのように私はから番号を取りますかそのクエリの出力と特定の文章を印刷する?上記のクエリでprintコマンドを使用しようとしましたが、エラーメッセージが表示されていました。

注:私はMacの端末からpsql/postgresを使用しています(構文上重要かどうかわかりません)。

+1

いくつかの測定値:[文字列関数と演算子](https://www.postgresql.org/docs/current/static/functions-string.html)(( '' ||演算子や '連結探し) '関数または' format() '関数)と[SQL GROUP BY文](https://www.w3schools.com/sql/sql_groupby.asp)を使用して' owner'フィールドを 'count (SELECT)句で(*) '集合を返します。ヒント: '所有者を選択する、所有者別にペットグループからカウントする(名前) 'から始まる。PS:" **端末**のpsql/postgresを使用しています " - ここではすべての開発者がターミナル :) – Abelisto

答えて

0

私はコメントでコメントを説明します。

SELECT 
    /* 
    * Cast the type of the first element to "text" so that we 
    * can be sure that we get the (text || text) or the (text || anynonarray) 
    * concatenation operator (run "\doS ||" in psql to get a list). 
    */ 
    CAST(owner AS text) 
     || ' has ' 
     /* now we can concatenate a "bigint" without casting */ 
     || count(name) 
     || ' pets.' 
FROM pets 
/* 
* The sum should be taken per owner, and we want one result row 
* per owner. This might be a problem if two people have the same name, 
* so one usually groups by a unique identifier instead. 
*/ 
GROUP BY owner; 
関連する問題