user7943858
user7943858

Reputation:

How to return only one row and one column name?

I am learning the Psql function by myself and I want to return only one row and one column name: dep_people and don't know how to solve this question in one row and one column name. Please help me to understand Psql function.

Preview table

SELECT * FROM test_sch.apollo_org_job_function;

|-------------------------------------------|
|organization_id |department      |no_people|
|-------------------------------------------|
|      2a        |accounting      |   3     | 
|      1a        |engineering     |   2     |
|      1a        |entrepreneurship|   1     | 
|      1a        |human resources |   4     |
|-------------------------------------------|

I am at here

SELECT
    department, no_people
FROM test_sch.apollo_org_job_function 
GROUP BY department, no_people 
ORDER BY department;

My return is:

|--------------------------|
|department      |no_people|
|--------------------------|
|accounting      |  3      | 
|engineering     |  2      |
|entrepreneurship|  1      | 
|human resources |  4      |
|--------------------------| 

Calling the function

select * from test_sch.return_dep_people('1a')
as f(dep_people text);

Expected output

------------------------------------------------------|
|dep_people                                           |
------------------------------------------------------|
|Engineering:2 , human_resources:4, entrepreneurship:1| 
-------------------------------------------------------

NOTE: the result should contains only 1 column named “dep_people” and only 1 row which is in String, (“Engineering:2 , human_resources:4, entrepreneurship:1” is a single String)

Upvotes: 1

Views: 266

Answers (3)

user7943858
user7943858

Reputation:

create function happy_return_dep_people(organisation_id text)
returns text
language plpgsql
as
$$
declare
   dep_people text;
begin
      SELECT STRING_AGG(d.department || ': ' || CAST(d.no_people AS text), ', ') into dep_people AS dep_people 
      FROM (
        SELECT department, no_people
      FROM test_sch.apollo_org_job_function
      WHERE organization_id = organisation_id
      GROUP BY department, no_people ORDER BY department) AS d;
   
   return dep_people;
end;
$$;
select * from test_sch.happy_return_dep_people('1a') 
as dep_people;

Upvotes: 0

Kitta
Kitta

Reputation: 324

I guess, STRING_AGG may help you. Something like this:

SELECT
  STRING_AGG(d.department || ': ' || CAST(d.no_people AS text), ', ') AS dep_people 
FROM ([your initial query]) AS d

Upvotes: 3

Slava Rozhnev
Slava Rozhnev

Reputation: 10163

You can achieve this using JSON_BUILD_OBJECT and JSON_AGG:

WITH data AS (
  SELECT department, COUNT(*) as "no_people"
  FROM apollo_org_job_function GROUP BY department ORDER BY department
) SELECT 
    JSON_AGG(JSON_BUILD_OBJECT(department, no_people)) as "dep_people"
FROM data;

PostgreSQL JSON_AGG JSON_BUILD_OBJECT

Upvotes: 2

Related Questions