Answer the question
In order to leave comments, you need to log in
Why is the query concatenating the wrong rows?
Hello, help me fix the error in the request:
There is a table:
SELECT
reservtable.sudovlad,
reservtable.summa,
reservtable.years,
((reservtable2.summa2 - reservtable.summa) / reservtable.summa * 100) AS percent,
reservtable2.summa2,
reservtable2.years2
FROM
(SELECT
sudovlad,
SUM(gruz_pass) AS summa,
EXTRACT(YEAR FROM data_vih_p_ot) AS years
FROM
ships
WHERE
sudovlad IN ('Русфлот, ООО', 'АрктикТранс ОИЛ, ООО','pere')
GROUP BY EXTRACT(YEAR FROM data_vih_p_ot)) reservtable,
(SELECT
sudovlad,
SUM(gruz_pass) AS summa2,
EXTRACT(YEAR FROM data_vih_p_ot) AS years2
FROM
ships
WHERE
sudovlad IN ('Русфлот, ООО', 'АрктикТранс ОИЛ, ООО','pere')
GROUP BY EXTRACT(YEAR FROM data_vih_p_ot)) reservtable2
WHERE
reservtable.years = 2018
OR reservtable2.years2 = 2017
Answer the question
In order to leave comments, you need to log in
It is better to use Joins for such queries
SELECT
ships.sudovlad,
s1.gruz_pass as summa,
EXTRACT(YEAR FROM s1.data_vih_p_ot) as years,
((s2.gruz_pass - s1.gruz_pass) / s1.gruz_pass * 100) AS percent,
s2.gruz_pass as summa2,
EXTRACT(YEAR FROM s2.data_vih_p_ot) AS years2
FROM ships
LEFT JOIN ships as s1
ON ships.sudovlad = s1.sudovlad AND EXTRACT(YEAR FROM s1.data_vih_p_ot)=2017 AND s1.sudovlad IN ('Русфлот, ООО', 'АрктикТранс ОИЛ, ООО','pere')
LEFT JOIN ships as s2
ON ships.sudovlad = s2.sudovlad AND EXTRACT(YEAR FROM s2.data_vih_p_ot)=2018 AND s2.sudovlad IN ('Русфлот, ООО', 'АрктикТранс ОИЛ, ООО','pere')
GROUP BY sudovlad
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question