Looked for an answer on this for a while and not quite sure how to ask it, much less answer it. I have a setup like the one below:
warehouse | company | charge code | date | price | other data |
---|---|---|---|---|---|
1 | comp 1 | boxes | 2022-1-1 | 3.00 | blah blah |
2 | comp 1 | bags | 2022-1-1 | 1.00 | blah blah |
3 | comp 1 | bag2 | 2022-2-5 | 1.00 | blah blah |
1 | comp 2 | boxes | 2022-1-1 | 3.00 | blah blah |
2 | comp 2 | bags | 2022-1-1 | 1.50 | blah blah |
3 | comp 2 | bag2 | 2022-2-5 | 2.00 | blah blah |
I am trying to make a query that will get me the prices that are different compared to the other companies in the same warehouse with the same charge code. For example, if it were to be run on the table above, it would result in
warehouse | company | charge code | date | price | other data |
---|---|---|---|---|---|
2 | comp 1 | bags | 2022-1-1 | 1.00 | blah blah |
2 | comp 2 | bags | 2022-1-1 | 1.50 | blah blah |
3 | comp 1 | bag2 | 2022-2-5 | 1.00 | blah blah |
3 | comp 2 | bag2 | 2022-2-5 | 2.00 | blah blah |
Since the box prices were the same for both companies in the same warehouse, they would be removed.
My code is
SELECT * FROM
(
WITH subquery AS (***LARGE IRRELEVANT SUBQUERY***)
SELECT distinct
warehouse, company, charge_code, date, price, other1, other2
FROM
subquery
WHERE(price)
IN
(SELECT distinct i1.price
FROM M_CHG_DATE_D i1 join M_CHG_DATE_D i2
ON i1.charge_code = i2.charge_code AND
i2.warehouse = i2.warehouse AND
i1.company != i2.company)
AND (warehouse, company, charge_code, date)
IN
(SELECT warehouse, company, charge_code, MAX(date)
FROM subquery
GROUP BY warehouse, company, charge_code)
)
WHERE company IN
('comp1', 'comp2', 'comp3', ... , 'comp n')
AND
warehouse NOT IN('list of warehouses')
ORDER BY company, charge_code, warehouse
Currently, instances where the companies have the same price in the same warehouse for the same charge code are not being filtered out. I would appreciate any help. Thanks.