0

I have the following three queries:

SELECT NAME,
    ABS(sum(UNITS)) as WK1 
FROM products 
    inner join stockdiary on  stockdiary.PRODUCT = products.ID  
where SUB_CATEGORY='LB40' 
    and DATENEW BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 7 DAY ) AND CURDATE( ) 
    and REASON = (-1) 
group by NAME 
order by CATEGORY;
SELECT NAME,
    ABS(sum(UNITS)) as WK2 
FROM products 
    inner join stockdiary on  stockdiary.PRODUCT = products.ID  
where SUB_CATEGORY='LB40' 
    and DATENEW between  curdate() - interval 14 day and curdate() - interval 8 day 
    and REASON = (-1) 
group by NAME 
order by CATEGORY;
SELECT NAME,
    ABS(sum(UNITS)) as wk3 
FROM products 
    inner join stockdiary on  stockdiary.PRODUCT = products.ID  
where SUB_CATEGORY='LB40' 
    and DATENEW between  curdate() - interval 21 day and curdate() - interval 15 day 
    and REASON = (-1) 
group by NAME 
order by CATEGORY;

Sample output from one of the queries:

NAME WK2
Longbeach 40/160 Original Ctn 2
Longbeach 40/160 Menthol Fresh Ctn 1
Longbeach 40 Fine Flavour Pkt 9
Longbeach 40 Rich Flavour Pkt 9
Longbeach 40 Menthol Fresh Pkt 5
Longbeach 40 Menthol Pkt 6
Longbeach 40 Select Pkt 5

How can I join the queries to get the following results?

NAME WK1 WK2 WK3
Longbeach 40/160 Original Ctn 2 3 4
... ... ... ...

The products table contains the following columns: ID, NAME, SUB_CATEGORY.

The stockckdiary table contains the following columns: PRODUCT, DATENEW, UNITS.

2
  • Please go to dbfiddle.uk and construct your table, input your data and please provide your desired result.
    – Vérace
    Jul 25, 2022 at 13:39
  • Read about pivoting.
    – Rick James
    Jul 26, 2022 at 4:23

1 Answer 1

1
SELECT name,
       ABS(SUM(CASE WHEN datenew BETWEEN CURRENT_DATE - INTERVAL 7 DAY 
                                 AND CURRENT_DATE 
                    THEN units
                    ELSE 0
                    END)) AS wk1,
       ABS(SUM(CASE WHEN datenew BETWEEN CURRENT_DATE - INTERVAL 14 DAY 
                                 AND CURRENT_DATE - INTERVAL 8 DAY
                    THEN units
                    ELSE 0
                    END)) AS wk2,
       ABS(SUM(CASE WHEN datenew BETWEEN CURRENT_DATE - INTERVAL 21 DAY 
                                 AND CURRENT_DATE - INTERVAL 15 DAY
                    THEN units
                    ELSE 0
                    END)) AS wk3
FROM products 
INNER JOIN stockdiary ON stockdiary.product = products.id  
WHERE sub_category='LB40' 
  AND datenew BETWEEN CURRENT_DATE - INTERVAL 21 DAY AND CURRENT_DATE
  AND reason = -1
GROUP BY name 
ORDER BY category;
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.