I have a table that called inventory_history_report which has a column detailed_disposition which can have one of three values SELLABLE, DEFECTIVE, CUSTOMER_DAMAGE.
I am trying to aggregate the rows into one row that will hold for each date the quantities for sellable, deffective and customer_damage. I need to group them by company, at fnsku.
This is what I came up with:
SELECT s1.company, 
    s1.fnsku, 
    s1.date, 
    s1.quantity AS defective_q, 
    s2.quantity AS sellable_q,
    s3.quantity AS customer_damage_q
FROM (
    SELECT id, sum(quantity) as quantity , company, date, fnsku, 
        detailed_disposition
    FROM inventory_history_report aihr 
    WHERE detailed_disposition = 'DEFECTIVE'
    GROUP BY date, company, fnsku, detailed_disposition
    ) AS s1
LEFT JOIN (
    SELECT id, sum(quantity) AS quantity , company, date, fnsku, 
        detailed_disposition
    FROM inventory_history_report aihr 
    WHERE detailed_disposition = 'SELLABLE'
    GROUP BY date, company, fnsku, detailed_disposition
    ) as s2 on (s2.fnsku = s1.fnsku AND 
                s2.company = s1.company AND
                s2.date = s1.date
                )
LEFT JOIN (
    SELECT id, sum(quantity) as quantity , company, date, fnsku, 
        detailed_disposition
    FROM inventory_history_report aihr 
    WHERE detailed_disposition = 'CUSTOMER_DAMAGED'
    GROUP BY date, company, fnsku, detailed_disposition
    ) AS s3 ON (s3.fnsku = s1.fnsku AND 
                s3.company = s1.company AND
                s3.date = s1.date
                )
I'm repeating myself in this query and I'm trying to find a way to reuse the derived table I use or at least part of it. I was trying to find a way to predefine a table but couldn't find a way, something like aliasing a derived table:
SELECT id, sum(quantity) as quantity , company, date, fnsku, detailed_disposition
FROM inventory_history_report ihr 
GROUP BY date, company, fnsku, detailed_disposition
and then filter it to my needs inside each join.
I tried to use some kind of a view like this:
CREATE VIEW aggregated_history AS
SELECT *
FROM amazon_inventory_history_report
GROUP BY date, company, fnsku, detailed_disposition
But I got an error denying me from doing it:
SQL Error [1142] [42000]: CREATE VIEW command denied to user for table 'aggregated_history'
I've also tried to use the WITH command but this as well gives error, that after some research got me to understand I am using version 5.7 which doesn't support the WITH keyword.
I cannot update the mysql server so this one is off the table nor can I elevate my permissions for this database.
Is there another way to do it, that will be less repetitive, more readable and preferable more efficient ?
 
    