Re: Subquery with multiple rows

Поиск
Список
Период
Сортировка
От Weiss, Jörg
Тема Re: Subquery with multiple rows
Дата
Msg-id 4B4E89127868BD458A795430BCF4FD1328F30B58@DVZSN-RA0325.bk.dvz-mv.net
обсуждение исходный текст
Ответ на Re: Subquery with multiple rows  (Benjamin Dietrich <b.dietrich@uni-tuebingen.de>)
Список pgsql-sql
Hi Benjamin!

Thank You! 

All Versions are working. 
I Think i will use the Version with FILTER clause.
The bad thing is, all versions are not much faster than my old version.

Regards, 
Jörg

-----Ursprüngliche Nachricht-----
Von: Benjamin Dietrich [mailto:b.dietrich@uni-tuebingen.de] 
Gesendet: Dienstag, 14. Juni 2016 11:39
An: Weiss, Jörg <J.Weiss@dvz-mv.de>
Cc: pgsql-sql@postgresql.org
Betreff: Re: [SQL] Subquery with multiple rows

Hi Jörg,

> How can I outsource a subquery?

maybe you could try to use "Common Table Expressions" and do something like:

WITH foerd_id AS      (SELECT foerd_id FROM foerds WHERE mass_id = '55896') SELECT DISTINCT a.*,
(       SELECT SUM(std)       FROM all_std       WHERE (a.status <=5 AND status = 5)         AND foerd_id IN (SELECT *
FROMfoerd_id)
 

) AS done_std,
(       SELECT SUM(anerk_std)       FROM all_std       WHERE (a.status >5 AND status < 5)         AND foerd_id IN
(SELECT* FROM foerd_id)
 
) AS accepted_std
FROM table_a a
WHERE a.mass_id = '55896’;

or with some more “outsourcing”:

WITH all_std_foerds AS      (SELECT *        FROM  all_std        WHERE foerd_id IN (SELECT foerd_id FROM foerds WHERE
mass_id= '55896')         AND status <= 5)
 
SELECT DISTINCT a.*,
(       SELECT SUM(std)       FROM all_std_foerds       WHERE (a.status <=5 AND status = 5)
) AS done_std,
(       SELECT SUM(anerk_std)       FROM all_std_foerds       WHERE (a.status >5 AND status < 5)
) AS accepted_std
FROM table_a a
WHERE a.mass_id = '55896';


Or maybe unnesting both aggregate subqueries in order to merge them and make use of FILTER-clauses
(https://www.postgresql.org/docs/9.5/static/sql-expressions.html#SYNTAX-AGGREGATES)might be a nice option. Something
like:

SELECT DISTINCT a.*,                SUM(std) FILTER (WHERE a.status <=5 AND s.status = 5) AS done_std,
SUM(anerk_std)FILTER (WHERE a.status >5 AND s.status < 5) AS accepted_std FROM table_a a, all_std s WHERE a.mass_id =
'55896'AND s.status<=5 AND s.foerd_id IN (SELECT foerd_id FROM foerds WHERE mass_id = '55896') GROUP BY a.mass_id,
a.status;

Regards, Benjamin



В списке pgsql-sql по дате отправления:

Предыдущее
От: Benjamin Dietrich
Дата:
Сообщение: Re: Subquery with multiple rows
Следующее
От: "David G. Johnston"
Дата:
Сообщение: Re: Subquery with multiple rows