I need to compare data on two different days in SQL. And I really need that in a single query since I need to use the results in pagination. Problem is, when I'm doing a self join it's results in duplicate columns since INNER JOIN
is a cartesian product.
Here's the code on sql fiddle
E.g.
SELECT * FROM `my_table` as t1
INNER JOIN my_table t2 ON t1.quality = t2.quality
WHERE (
t1.day = '2015-01-08' OR t1.day = '2015-01-09' OR
t2.day = '2015-01-08' OR t2.day = '2015-01-09'
)
Two questions:
- How do I rewrite that go get one row per JOIN on quality?
- Will it still work if some corresponding row (on quality) is missing from one of the days?
EDIT
Here's the input:
INSERT INTO my_table
(quality, quantity, day)
VALUES
('A', 1, '2015-01-15'),
('B', 2, '2015-01-15'),
('B', 0, '2015-01-10');
And the desired output is:
QUALITY | QUANTITY | T1.QUANTITY - T2.QUANTITY
A 1 0 (or NULL?)
B 2 2
Explanation:
There are unique values on each date. So we see only A and B quality. For B- there is appropriate B on another date. For A - there isn't. Therefore the difference for B is 2 (higher date minus lower). The difference for A is 0 because there's nothing to subtract from.