Auf eine previous question stellte ich eine ähnliche Frage, die auf eine Hilfstabelle als Teil der Kriterien für die Aufteilung der Daten verließ. Es scheint, dass mein jetziges Ziel einfacher ist, aber ich konnte es nicht herausfinden.Zusammengesetzten Text basierend auf einem Kriterium
Angesichts der Tabelle:
CREATE TABLE conversations (id int, record_id int, is_response bool, text text);
INSERT INTO conversations VALUES
(1, 1, false, 'in text 1')
, (2, 1, true , 'response text 1')
, (3, 1, false, 'in text 2')
, (4, 1, true , 'response text 2')
, (5, 1, true , 'response text 3')
, (6, 2, false, 'in text 1')
, (7, 2, true , 'response text 1')
, (8, 2, false, 'in text 2')
, (9, 2, true , 'response text 2')
, (10, 2, true , 'response text 3');
Ich möchte den Text aggregieren basierend auf dem is_response
Wert und geben die folgenden:
record_id | aggregated_text |
----------+---------------------------------------------------+
1 |in text 1 response text 1 |
----------+---------------------------------------------------+
1 |in text 2 response text 2 response text 3 |
----------+---------------------------------------------------+
2 |in text 1 response text 1 |
----------+---------------------------------------------------+
2 |in text 2 response text 2 response text 3 |
ich die folgende Abfrage habe versucht, aber es funktioniert nicht Um zwei Antworten hintereinander zu aggregieren, ist IE: is_response in einer Sequenz wahr.
SELECT
record_id,
string_agg(text, ' ' ORDER BY id) AS aggregated_text
FROM (
SELECT
*,
coalesce(sum(incl::integer) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) AS grp
FROM (
SELECT *, is_response as incl
FROM conversations
) c
) c1
GROUP BY record_id, grp
HAVING bool_or(incl)
ORDER BY max(id);
Die Ausgabe meiner Abfrage kommt noch hinzu, eine weitere Zeile für die folgende is_response Zeile wie folgt:
record_id | aggregated_text |
----------+---------------------------------------------------+
1 |in text 1 response text 1 |
----------+---------------------------------------------------+
1 |in text 2 response text 2 |
----------+---------------------------------------------------+
1 |response text 3 |
----------+---------------------------------------------------+
2 |in text 1 response text 1 |
----------+---------------------------------------------------+
2 |in text 2 response text 2 |
----------+---------------------------------------------------+
2 | response text 3 |
----------+---------------------------------------------------+
Wie kann ich es beheben?
Sieht so aus, als ob Sie eine Fensterfunktion für mich brauchen. – jpmc26
Vielen Dank für Ihre Antwort, können Sie mit einem Codebeispiel helfen? –
Habe gerade keine Zeit. Ich wollte Ihnen nur einen Anhaltspunkt geben, um etwas zu sehen. – jpmc26