O
O
Oleg Seledets2019-01-14 19:26:10
MySQL
Oleg Seledets, 2019-01-14 19:26:10

Why is the query concatenating the wrong rows?

Hello, help me fix the error in the request:
There is a table:
5c3cb2c6e1836632226983.png

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

Outputs the result
5c3cb2b01f984937382222.png
It is necessary that the result be of the form:
Rusflot, LLC' 14 2018 -22.2 18 2017
ArcticTrans OIL 28 2018 100 0 2017
pere 69 2018 475 12 2017
Some shipowner has data for 2018 and 2017 transportation, it happens that the carrier in 2017 or 2018 did not participate in transportation, so the data is only for one year.
But you need to get a pivot table in which:
  1. shipowner
  2. The amount of transported cargo
  3. 2018
  4. Percentage as a difference
  5. The amount of transported cargo
  6. 2017

If there is no data, for example for 2017, so that those columns have 0 or nothing at all.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
di, 2019-01-14
@oleja1ee7

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 question

Ask a Question

731 491 924 answers to any question