2017-06-26 38 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'; 

但是我怎麼取數該查詢的輸出並打印出特定的句子?我試圖用上面的查詢使用打印命令,但得到一個錯誤消息。

注意:我在Mac上使用終端中的psql/postgres(不知道這是否對語法有影響)。

+1

一些讀數:[字符串函數和操作](https://www.postgresql.org/docs/current/static/functions-string.html)(查找''||運營商或'的concat( )函數或'format()'函數)和[SQL GROUP BY語句](https://www.w3schools.com/sql/sql_groupby.asp),如果您要將'owner'字段與'count (*)'在'SELECT'子句中聚合。提示:從'選擇所有者開始,根據所有者從寵物組計數(名稱);'PS:+ 1代表「_I使用來自**終端的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;