Re: using a common key value on both sides of a union ?

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: David Gauthier <davegauthierpg(at)gmail(dot)com>
Cc: Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: using a common key value on both sides of a union ?
Date: 2020-04-01 23:46:04
Message-ID: CAKFQuwa+5A-GtFW+inV_Z28vg_Wh99-=d71bfFq_kafaL1Psvg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wednesday, April 1, 2020, David Gauthier <davegauthierpg(at)gmail(dot)com>
wrote:

> psql (9.6.7, server 11.3) on linux
>
> I want to do something like this
> (intentionally bad sql but will illustrate the need)
>
> select s.name,s.grade from students s where s.class='math'
> union
> select 'whole class', class_grade from all_classes where class=s.class
>
> Of course it's that "where class=s.class" that's a foul.
>
> In English, I want a list of each math student and their grade and then
> append one more record for the entire class, a record that comes from a
> different table but narrowed down to that one class.
>
> I don't care if union isn't the right approach. Anything that works is
> welcome !
>

You are correct this model seems undesirable but given you have it why
doesn’t the following work for you?

Select students where class = ‘math’
Union all
Select all_classes where class = ‘math’

The generally better query is:
Select from students ... group by rollup

https://www.postgresql.org/docs/9.6/queries-table-expressions.html#QUERIES-GROUPING-SETS

David J.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message David Steele 2020-04-02 01:09:20 Re: It is possible to force periodically switch xlog?
Previous Message David Gauthier 2020-04-01 23:39:14 using a common key value on both sides of a union ?