Michi :
Table SQL Fiddle:
CREATE TABLE Sales_Planning (
Time_Stamp DATE,
Campaign VARCHAR(255),
Expected_Sales VARCHAR(255)
);
INSERT INTO Sales_Planning
(Time_Stamp, Campaign, Expected_Sales)
VALUES
("2019-11-04", "Campaign01", "300"),
("2019-11-04", "Campaign02", "300"),
("2019-11-04", "Campaign03", "300"),
("2019-11-04", "Campaign04", "300"),
("2019-11-05", "Campaign01", "600"),
("2019-11-05", "Campaign02", "800"),
("2019-11-05", "Campaign03", "300"),
("2019-11-05", "Campaign04", "300"),
("2019-11-06", "Campaign01", "300"),
("2019-11-06", "Campaign02", "200"),
("2019-11-06", "Campaign03", "400"),
("2019-11-06", "Campaign04", "500");
In the table I have the history of the Sales_Planning
of different campaigns
.
As you can see every day the Expected_Sales
are stored into this table using a Time_Stamp
.
Ideally, once the Expected_Sales
are inserted they never change.
However, sometimes the Expected_Salse
are changed.
Now, I want to identify the Campaigns
that have changed their Expected_Sales
for example between
Time_Stamp_A 2019-11-04
Time_Stamp_B 2019-11-06
The result should look like this:
Campaign Time_Stamp_A Time_Stamp_B Expected_Sales_A Expected_Sales_B
Campaign02 2019-11-04 2019-11-06 300 200
Campaign03 2019-11-04 2019-11-06 300 400
Campaign04 2019-11-04 2019-11-06 300 500
The closest I came so far is this query:
SELECT
Campaign,
Time_Stamp,
Expected_Sales,
(CASE WHEN Time_Stamp = "2019-11-04" THEN "Time_Stamp_A" ELSE "Time_Stamp_B" END) AS Time_Stamp
FROM Sales_Planning
WHERE
Time_Stamp = "2019-11-04"
OR Time_Stamp = "2019-11-06";
What do I need to change in my SQL to get the result I need?
Gordon Linoff :
Is this what you want?
SELECT sp1.Campaign, sp1.Time_Stamp, sp1.Expected_Sales,
sp2.Time_Stamp, sp2.Expected_Sales
FROM Sales_Planning sp1 JOIN
Sales_Planning sp2
ON sp1.campaign = sp2.campaign AND
sp1.Time_Stamp = '2019-11-04' AND
sp2.Time_Stamp = '2019-11-06'
WHERE sp1.Expected_Sales <> sp2.Expected_Sales;
This seems to return what you want.