Re: Need query

From: Thomas Kellerer <shammat(at)gmx(dot)net>
To: pgsql-admin(at)lists(dot)postgresql(dot)org
Subject: Re: Need query
Date: 2021-07-17 08:32:45
Message-ID: d3309e65-ddff-439e-49a1-7a42a0479001@gmx.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin

Firthouse banu schrieb am 17.07.2021 um 09:24:
> Table1
> Name      Fruit
> A              Mango
> A              Apple
> A               Grape
> B.              Mango
> B.              Mango
> A.              Mango
> A.              Apple
>
> Output
> Name.   Mango   Apple   Grape
> A.           2.            2.          1
> B.           2.             0.         0
>
> Can anyone write query to get this desired output from table one in Postgres please.

In my opinion, filtered aggregation is the most flexible way to do this kind of thing

select name,
count(*) filter (where fruit = 'Mango') as mango,
count(*) filter (where fruit = 'Apple') as apple,
count(*) filter (where fruit = 'Grape') as grape
from the_table
group by name
order by name;

And before you ask: it's not really possible to make this dynamic, so that the number
of columns "automagically" increases when you have more fruits. One fundamental
restriction of the SQL language is that the number and types of all columns
must be known to the database when the query is parsed. It can't change
the columns as a result of the query itself.

In response to

  • Need query at 2021-07-17 07:24:57 from Firthouse banu

Responses

Browse pgsql-admin by date

  From Date Subject
Next Message Caetano Traina Junior 2021-07-18 13:19:48 Re: Need query
Previous Message Imre Samu 2021-07-17 08:20:50 Re: Need query