如何使用SQL / postgresql打印自定义短语+计算?

时间:2017-06-26 18:49:02

标签: 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 个答案:

答案 0 :(得分: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;