I have 3 tables: invoice order, and salesteam. I want to create a query to determine the total order value for each sales representative in each company.
I am receiving an error when running my query. Could someone provide some suggestions on how to troubleshoot? Thank you!
invoice:
Order_Id,Date,Meal_Id,Company_Id,Date_of_Meal,Participants,Meal_Price,Type_of_Meal
839FKFW2LLX4LMBB,27-05-2016,INBUX904GIHI8YBD,LJKS5NK6788CYMUU,2016-05-31 07:00:00+02:00,['David Bishop'],469,Breakfast
97OX39BGVMHODLJM,27-09-2018,J0MMOOPP709DIDIE,LJKS5NK6788CYMUU,2018-10-01 20:00:00+02:00,['David Bishop'],22,Dinner
041ORQM5OIHTIU6L,24-08-2014,E4UJLQNCI16UX5CS,LJKS5NK6788CYMUU,2014-08-23 14:00:00+02:00,['Karen Stansell'],314,Lunch
YT796QI18WNGZ7ZJ,12-04-2014,C9SDFHF7553BE247,LJKS5NK6788CYMUU,2014-04-07 21:00:00+02:00,['Addie Patino'],438,Dinner
6YLROQT27B6HRF4E,28-07-2015,48EQXS6IHYNZDDZ5,LJKS5NK6788CYMUU,2015-07-27 14:00:00+02:00,['Addie Patino' 'Susan Guerrero'],690,Lunch
AT0R4DFYYAFOC88Q,21-07-2014,W48JPR1UYWJ18NC6,LJKS5NK6788CYMUU,2014-07-17 20:00:00+02:00,['David Bishop' 'Susan Guerrero' 'Karen Stansell'],181,Dinner
2DDN2LHS7G85GKPQ,29-04-2014,1MKLAKBOE3SP7YUL,LJKS5NK6788CYMUU,2014-04-30 21:00:00+02:00,['Susan Guerrero' 'David Bishop'],14,Dinner
FM608JK1N01BPUQN,08-05-2014,E8WJZ1FOSKZD2MJN,36MFTZOYMTAJP1RK,2014-05-07 09:00:00+02:00,['Amanda Knowles' 'Cheryl Feaster' 'Ginger Hoagland' 'Michael White'],320,Breakfast
orders:
Order_Id,Company_Id,Company_Name,Date,Order_Value,Converted
80EYLOKP9E762WKG,LJKS5NK6788CYMUU,Chimera-Chasing Casbah,18-02-2017,4875,1
TLEXR1HZWTUTBHPB,LJKS5NK6788CYMUU,Chimera-Chasing Casbah,30-07-2015,8425,0
839FKFW2LLX4LMBB,LJKS5NK6788CYMUU,Chimera-Chasing Casbah,27-05-2016,4837,0
97OX39BGVMHODLJM,LJKS5NK6788CYMUU,Chimera-Chasing Casbah,2018-09-27,343,0
5T4LGH4XGBWOD49Z,LJKS5NK6788CYMUU,Chimera-Chasing Casbah,2016-01-14,983,0
041ORQM5OIHTIU6L,LJKS5NK6788CYMUU,Chimera-Chasing Casbah,2014-08-24,4185,0
8QUW0UXQ3XHIL56W,LJKS5NK6788CYMUU,Chimera-Chasing Casbah,2018-09-06,3186,0
salesteam:
Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id
Jessie Mcallister,97UNNAT790E0WM4N,Chimera-Chasing Casbah,LJKS5NK6788CYMUU
Jessie Mcallister,97UNNAT790E0WM4N,Two-Mile Grab,H3JRC7XX7WJAD4ZO
Jessie Mcallister,97UNNAT790E0WM4N,Three-Men-And-A-Helper Congo'S,HB25MDZR0MGCQUGX
Jessie Mcallister,97UNNAT790E0WM4N,Paleocortical Boatloads,NUQS9SHQH6IU92V8
Jessie Mcallister,97UNNAT790E0WM4N,Editorial Paintbrush,PQ79N68UEQ9FFCPU
Jessie Mcallister,97UNNAT790E0WM4N,Victorian Aim,93DU98KT3NZCOW58
Jessie Mcallister,97UNNAT790E0WM4N,Industrial Opinions,BQMPJF0W2Z2E0PEW
Lois Bowers,RRD2R9XMAJDP7TUY,Fantastic Re-Enactments,W2X6NP1JBOKWCO33
Lois Bowers,RRD2R9XMAJDP7TUY,Infamous Inoculation,D459BZ8Z7N1KAFGU
Lois Bowers,RRD2R9XMAJDP7TUY,Simple-Seeming Tenure,MR6NETSKD2PSN54L
Query:
SELECT s.Sales_Rep, SUM(o.Order_Value) AS Total_Order_Value
FROM salesteam s
JOIN orders o ON s.Company_Id = o.Company_Id
JOIN invoice i ON o.Order_Id = i.Order_Id
WHERE DISTINCT s.Company_Name
GROUP BY s.Sales_Rep;
Error Message:
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT s.Company_Name\n GROUP BY s.Sales_Rep' at line 6")
What you have tried to do is close to what you need, the issue in your code is the WHERE DISTINCT s.Company_Name you cannot use DISTINCT keyword in the WHERE clause.
Schema (MySQL v8.0)
CREATE TABLE invoice
(
Order_Id VARCHAR(512),
Date VARCHAR(512),
Meal_Id VARCHAR(512),
Company_Id VARCHAR(512),
Date_of_Meal VARCHAR(512),
Participants VARCHAR(512),
Meal_Price INT,
Type_of_Meal VARCHAR(512)
);
INSERT INTO invoice (Order_Id, Date, Meal_Id, Company_Id, Date_of_Meal, Participants, Meal_Price, Type_of_Meal) VALUES ('839FKFW2LLX4LMBB', '27-05-2016', 'INBUX904GIHI8YBD', 'LJKS5NK6788CYMUU', '2016-05-31 07:00:00+02:00', '[\'David Bishop\']', '469', 'Breakfast');
INSERT INTO invoice (Order_Id, Date, Meal_Id, Company_Id, Date_of_Meal, Participants, Meal_Price, Type_of_Meal) VALUES ('97OX39BGVMHODLJM', '27-09-2018', 'J0MMOOPP709DIDIE', 'LJKS5NK6788CYMUU', '2018-10-01 20:00:00+02:00', '[\'David Bishop\']', '22', 'Dinner');
INSERT INTO invoice (Order_Id, Date, Meal_Id, Company_Id, Date_of_Meal, Participants, Meal_Price, Type_of_Meal) VALUES ('041ORQM5OIHTIU6L', '24-08-2014', 'E4UJLQNCI16UX5CS', 'LJKS5NK6788CYMUU', '2014-08-23 14:00:00+02:00', '[\'Karen Stansell\']', '314', 'Lunch');
INSERT INTO invoice (Order_Id, Date, Meal_Id, Company_Id, Date_of_Meal, Participants, Meal_Price, Type_of_Meal) VALUES ('YT796QI18WNGZ7ZJ', '12-04-2014', 'C9SDFHF7553BE247', 'LJKS5NK6788CYMUU', '2014-04-07 21:00:00+02:00', '[\'Addie Patino\']', '438', 'Dinner');
INSERT INTO invoice (Order_Id, Date, Meal_Id, Company_Id, Date_of_Meal, Participants, Meal_Price, Type_of_Meal) VALUES ('6YLROQT27B6HRF4E', '28-07-2015', '48EQXS6IHYNZDDZ5', 'LJKS5NK6788CYMUU', '2015-07-27 14:00:00+02:00', '[\'Addie Patino\' \'Susan Guerrero\']', '690', 'Lunch');
INSERT INTO invoice (Order_Id, Date, Meal_Id, Company_Id, Date_of_Meal, Participants, Meal_Price, Type_of_Meal) VALUES ('AT0R4DFYYAFOC88Q', '21-07-2014', 'W48JPR1UYWJ18NC6', 'LJKS5NK6788CYMUU', '2014-07-17 20:00:00+02:00', '[\'David Bishop\' \'Susan Guerrero\' \'Karen Stansell\']', '181', 'Dinner');
INSERT INTO invoice (Order_Id, Date, Meal_Id, Company_Id, Date_of_Meal, Participants, Meal_Price, Type_of_Meal) VALUES ('2DDN2LHS7G85GKPQ', '29-04-2014', '1MKLAKBOE3SP7YUL', 'LJKS5NK6788CYMUU', '2014-04-30 21:00:00+02:00', '[\'Susan Guerrero\' \'David Bishop\']', '14', 'Dinner');
INSERT INTO invoice (Order_Id, Date, Meal_Id, Company_Id, Date_of_Meal, Participants, Meal_Price, Type_of_Meal) VALUES ('FM608JK1N01BPUQN', '08-05-2014', 'E8WJZ1FOSKZD2MJN', '36MFTZOYMTAJP1RK', '2014-05-07 09:00:00+02:00', '[\'Amanda Knowles\' \'Cheryl Feaster\' \'Ginger Hoagland\' \'Michael White\']', '320', 'Breakfast');
CREATE TABLE orders
(
Order_Id VARCHAR(512),
Company_Id VARCHAR(512),
Company_Name VARCHAR(512),
Date VARCHAR(512),
Order_Value INT,
Converted VARCHAR(512)
);
INSERT INTO orders (Order_Id, Company_Id, Company_Name, Date, Order_Value, Converted) VALUES ('80EYLOKP9E762WKG', 'LJKS5NK6788CYMUU', 'Chimera-Chasing Casbah', '18-02-2017', '4875', '1');
INSERT INTO orders (Order_Id, Company_Id, Company_Name, Date, Order_Value, Converted) VALUES ('TLEXR1HZWTUTBHPB', 'LJKS5NK6788CYMUU', 'Chimera-Chasing Casbah', '30-07-2015', '8425', '0');
INSERT INTO orders (Order_Id, Company_Id, Company_Name, Date, Order_Value, Converted) VALUES ('839FKFW2LLX4LMBB', 'LJKS5NK6788CYMUU', 'Chimera-Chasing Casbah', '27-05-2016', '4837', '0');
INSERT INTO orders (Order_Id, Company_Id, Company_Name, Date, Order_Value, Converted) VALUES ('97OX39BGVMHODLJM', 'LJKS5NK6788CYMUU', 'Chimera-Chasing Casbah', '2018-09-27', '343', '0');
INSERT INTO orders (Order_Id, Company_Id, Company_Name, Date, Order_Value, Converted) VALUES ('5T4LGH4XGBWOD49Z', 'LJKS5NK6788CYMUU', 'Chimera-Chasing Casbah', '2016-01-14', '983', '0');
INSERT INTO orders (Order_Id, Company_Id, Company_Name, Date, Order_Value, Converted) VALUES ('041ORQM5OIHTIU6L', 'LJKS5NK6788CYMUU', 'Chimera-Chasing Casbah', '2014-08-24', '4185', '0');
INSERT INTO orders (Order_Id, Company_Id, Company_Name, Date, Order_Value, Converted) VALUES ('8QUW0UXQ3XHIL56W', 'LJKS5NK6788CYMUU', 'Chimera-Chasing Casbah', '2018-09-06', '3186', '0');
CREATE TABLE salesteam
(
Sales_Rep VARCHAR(512),
Sales_Rep_Id VARCHAR(512),
Company_Name VARCHAR(512),
Company_Id VARCHAR(512)
);
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Jessie Mcallister', '97UNNAT790E0WM4N', 'Chimera-Chasing Casbah', 'LJKS5NK6788CYMUU');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Jessie Mcallister', '97UNNAT790E0WM4N', 'Two-Mile Grab', 'H3JRC7XX7WJAD4ZO');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Jessie Mcallister', '97UNNAT790E0WM4N', 'Three-Men-And-A-Helper CongoS', 'HB25MDZR0MGCQUGX');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Jessie Mcallister', '97UNNAT790E0WM4N', 'Paleocortical Boatloads', 'NUQS9SHQH6IU92V8');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Jessie Mcallister', '97UNNAT790E0WM4N', 'Editorial Paintbrush', 'PQ79N68UEQ9FFCPU');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Jessie Mcallister', '97UNNAT790E0WM4N', 'Victorian Aim', '93DU98KT3NZCOW58');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Jessie Mcallister', '97UNNAT790E0WM4N', 'Industrial Opinions', 'BQMPJF0W2Z2E0PEW');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Lois Bowers', 'RRD2R9XMAJDP7TUY', 'Fantastic Re-Enactments', 'W2X6NP1JBOKWCO33');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Lois Bowers', 'RRD2R9XMAJDP7TUY', 'Infamous Inoculation', 'D459BZ8Z7N1KAFGU');
INSERT INTO salesteam (Sales_Rep, Sales_Rep_Id, Company_Name, Company_Id) VALUES ('Lois Bowers', 'RRD2R9XMAJDP7TUY', 'Simple-Seeming Tenure', 'MR6NETSKD2PSN54L');
Query #1
SELECT S.Sales_Rep, S.Sales_Rep_Id, S.Company_Name, SUM(O.Order_Value)
FROM invoice I
JOIN orders O ON O.Order_ID = I.Order_Id AND O.Company_Id = I.Company_Id
JOIN salesteam S ON I.Company_Id = S.Company_Id
GROUP BY S.Sales_Rep, S.Sales_Rep_Id, S.Company_Name;
Sales_Rep
Sales_Rep_Id
Company_Name
SUM(O.Order_Value)
Jessie Mcallister
97UNNAT790E0WM4N
Chimera-Chasing Casbah
9365
Note: The salesteam csv data seems to have a ' so you might need to keep an eye out and handle this when you insert the data into your tables. e.g: Jessie Mcallister,97UNNAT790E0WM4N,Three-Men-And-A-Helper Congo'S,HB25MDZR0MGCQUGX
Related
I am trying to write a query where I need to get
A list containing the name (surname and first name) of any employee that has picked any product(s) for a stock request.
I am confused about this as all this information is scattered amongst different tables.
The contents of my tables are as follows;
Picking_List (warehouseID, locationID, productNum, requestNum, quantityPicked, datePicked, pickerStaffID)
INSERT INTO Picking_List (warehouseID, locationID, productNum, requestNum, quantityPicked, datePicked, pickerStaffID)
VALUES ('1004','123','10','154','2','10/10/2021','4561');
INSERT INTO Picking_List (warehouseID, locationID, productNum, requestNum, quantityPicked, datePicked, pickerStaffID)
VALUES ('1004','21','143','283','1','07/07/2021','1832');
INSERT INTO Picking_List (warehouseID, locationID, productNum, requestNum, quantityPicked, datePicked, pickerStaffID)
VALUES ('1004','84','25','321','4','12/02/2020','3313');
INSERT INTO Picking_List (warehouseID, locationID, productNum, requestNum, quantityPicked, datePicked, pickerStaffID)
VALUES ('1004','76','130','254','8','02/02/2019','2121');
INSERT INTO Picking_List (warehouseID, locationID, productNum, requestNum, quantityPicked, datePicked, pickerStaffID)
VALUES ('1004','98','223','78','3','06/04/2021','1020');
Employee (StaffID, surname, firstName, dob, street, city, state, postcode, salary , WarehouseID, SupervisedBy)
INSERT INTO Employee (staffID,surname, firstName, dob, street, city, state, postcode, salary, warehouseID, supervisedBy)
VALUES ('4561', 'Snow', 'John', '30/12/1995', 'vulture', 'Brisbane', 'QLD', '4010', '60,000', '1004', 'Nosheen');
INSERT INTO Employee (staffID,surname, firstName, dob, street, city, state, postcode, salary, warehouseID, supervisedBy)
VALUES ('1832', 'Turner', 'Mike', '01/07/2000', 'vulture', 'Brisbane', 'QLD', '4010', '66,000', '1004', 'Nosheen');
INSERT INTO Employee (staffID,surname, firstName, dob, street, city, state, postcode, salary, warehouseID, supervisedBy)
VALUES ('3313', 'Smith', 'Jake', '06/06/1996', 'vulture', 'Brisbane', 'QLD', '4010', '55,000', '1004', 'Nosheen');
INSERT INTO Employee (staffID,surname, firstName, dob, street, city, state, postcode, salary, warehouseID, supervisedBy)
VALUES ('2121', 'Jones', 'Sally', '26/04/1984', 'vulture', 'Brisbane', 'QLD', '4010', '78,000', '1004', 'Nosheen');
INSERT INTO Employee (staffID,surname, firstName, dob, street, city, state, postcode, salary, warehouseID, supervisedBy)
VALUES ('1020', 'Wilson', 'Andrew', '11/03/1980', 'vulture', 'Brisbane', 'QLD', '4010', '100,000', '1004', 'Nosheen');
Stock_Request (requestNum, requestDate, clientNum )
INSERT INTO Stock_Request (requestNum,requestDate, clientNum)
VALUES ('123','10/12/2021','1234');
INSERT INTO Stock_Request (requestNum,requestDate, clientNum)
VALUES ('141','21/08/2020','134');
INSERT INTO Stock_Request (requestNum,requestDate, clientNum)
VALUES ('15','05/02/2021','434');
INSERT INTO Stock_Request (requestNum,requestDate, clientNum)
VALUES ('223','11/03/2019','472');
INSERT INTO Stock_Request (requestNum,requestDate, clientNum)
VALUES ('535','10/10/2020','1402');
Request_List (requestNum , productNum, qtyRequested )
INSERT INTO Request_List (requestNum, productNum, qtyRequested)
VALUES ('525','232','2');
INSERT INTO Request_List (requestNum, productNum, qtyRequested)
VALUES ('111','104','1');
INSERT INTO Request_List (requestNum, productNum, qtyRequested)
VALUES ('145','32','5');
INSERT INTO Request_List (requestNum, productNum, qtyRequested)
VALUES ('674','100','10');
INSERT INTO Request_List (requestNum, productNum, qtyRequested)
VALUES ('5','22','4';
so far this is what I have got.
SELECT C.surname,
C.firstName, CA.pickerStaffID
FROM employee AS C INNER JOIN Picking_List AS CA
ORDER BY employee ASC;
I am unsure if I have included everything I need in my query as per the task. Any help or advice would be appreciated as I am relatively new to SQL.
Try this:
SELECT
concat(e.surname, ', ', e.firstName) as fullName
FROM
Picking_List pl
INNER JOIN
Employee e ON e.StaffID = pl.pickerStaffID
WHERE
pl.requestNum = :RequestNumberToLookFor
:RequestNumberToLookFor is the request Number of the request you are looking for. Use appropriate parameterization syntax for your code.
I have a problem. How can I write this sql statment without roll up?
I want to get the same result, but without rollup. The result should look like the image below.
my query
select state, city, sum((sales.retail_price - products.wholesale_price) *
sales.quantity) as profit
from products, sales
where sales.product_id = products.product_id
group by state, city WITH ROLLUP
order by state is null, city is null, state, city ;
my schema
-- Create some tables and insert some rows.
create table products (product_id integer, wholesale_price real);
insert into products (product_id, wholesale_price) values
(1, 1.00),
(2, 2.00);
create table sales (product_id integer, retail_price real,
quantity integer, city varchar, state varchar);
insert into sales (product_id, retail_price, quantity, city, state) values
(1, 2.00, 1, 'SF', 'CA'),
(1, 2.00, 2, 'SJ', 'CA'),
(2, 5.00, 4, 'SF', 'CA'),
(2, 5.00, 8, 'SJ', 'CA'),
(2, 5.00, 16, 'Miami', 'FL'),
(2, 5.00, 32, 'Orlando', 'FL'),
(2, 5.00, 64, 'SJ', 'PR');
You must use an UNION operation, as follow:
The first query returns the SUM grouped by state and city, the second only for state, and the third (without group by) for all rows
select state, city, sum((sales.retail_price - products.wholesale_price) *
sales.quantity) as profit
from products, sales
where sales.product_id = products.product_id
group by state, city
UNION ALL
select state, NULL, sum((sales.retail_price - products.wholesale_price) *
sales.quantity) as profit
from products, sales
where sales.product_id = products.product_id
group by state
UNION ALL
select NULL, NULL, sum((sales.retail_price - products.wholesale_price) *
sales.quantity) as profit
from products, sales
where sales.product_id = products.product_id;
I have a problem. My MySQL query doesn't work. How could I fix this ?
my query
select state, city, sum((sales.retail_price - products.wholesale_price) * sales.quantity) as profit
from products, sales
where sales.product_id = products.product_id
group by rollup (state, city)
order by state, city;
my error
11:39:12 select state, city, sum((sales.retail_price - products.wholesale_price) * sales.quantity) as profit from products, sales where sales.product_id = products.product_id group by rollup (state, city) order by state, city Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(state, city) order by state, city' at line 4 0.000 sec
my schema
-- Create some tables and insert some rows.
create table products (product_id integer, wholesale_price real);
insert into products (product_id, wholesale_price) values
(1, 1.00),
(2, 2.00);
create table sales (product_id integer, retail_price real,
quantity integer, city varchar, state varchar);
insert into sales (product_id, retail_price, quantity, city, state) values
(1, 2.00, 1, 'SF', 'CA'),
(1, 2.00, 2, 'SJ', 'CA'),
(2, 5.00, 4, 'SF', 'CA'),
(2, 5.00, 8, 'SJ', 'CA'),
(2, 5.00, 16, 'Miami', 'FL'),
(2, 5.00, 32, 'Orlando', 'FL'),
(2, 5.00, 64, 'SJ', 'PR');
Try this:
select state, city, sum((sales.retail_price - products.wholesale_price) *
sales.quantity) as profit
from products, sales
where sales.product_id = products.product_id
group by state, city WITH ROLLUP
order by state, city;
You can see here the ROLL UP behaviour
I have 3 tables:
sales_fact (fact_date, prod_id, fact_sum)
sales_pred (pred_date, prod_id, pred_sum)
product (prod_id, name, price)
I need to make up a report which consists of the following columns:
Year
Month
Name of the product
Fact sales
Predicted saled
Deviation
If Fact sales is null, then deviation = Predicted saled;
If Predicted saled is null, then deviation = -Fact sales
I have difficulties in the last condition. Help me to understand my mistake
My code:
SELECT year(fact_date) AS Year,
month(fact_date) AS Month,
product.name AS Name,
ROUND(SUM(fact_sum), 2) AS Fact,
ROUND(SUM(pred_sum), 2) AS Prediction,
(CASE
WHEN SUM(pred_sum) IS NULL AND SUM(fact_sum) IS NOT NULL
THEN ROUND(-(SUM(fact_sum)), 2)
WHEN SUM(fact_sum) IS NULL AND SUM(pred_sum) IS NOT NULL
THEN ROUND(SUM(pred_sum)), 2)
WHEN SUM(pred_sum) IS NOT NULL AND SUM(fact_sum) IS NOT NULL
THEN ROUND(SUM(pred_sum) - (SUM(fact_sum)), 2)
ELSE 0 END AS Deviation
FROM sales_fact
LEFT JOIN product ON sales_fact.prod_id = product.prod_id
LEFT JOIN sales_pred ON sales_pred.prod_id = product.prod_id AND sales_pred.pred_date = sales_fact.fact_date
GROUP BY product.name, month(fact_date), year(fact_date);
CODE FOR CREATING TABLES:
create table sales_fact (fact_date date, prod_id varchar(30), fact_sum float);
insert into sales_fact (fact_date, prod_id, fact_sum) values ('2016-03-25', '2271145', 93.31);
insert into sales_fact (fact_date, prod_id, fact_sum) values ('2016-04-25', '2271146', 13.31);
insert into sales_fact (fact_date, prod_id, fact_sum) values ('2016-05-25', '2271147', 83.31);
insert into sales_fact (fact_date, prod_id, fact_sum) values ('2016-03-25', '2271145', 43.31);
insert into sales_fact (fact_date, prod_id, fact_sum) values ('2016-07-25', '2271148', 73.31);
insert into sales_fact (fact_date, prod_id, fact_sum) values ('2016-07-25', '2271147', 13.31);
insert into sales_fact (fact_date, prod_id, fact_sum) values ('2016-08-25', '2271149', 43.31);
insert into sales_fact (fact_date, prod_id, fact_sum) values ('2016-09-25', '2271148', 33.31);
create table sales_pred (pred_date date, prod_id varchar(30), pred_sum float);
insert into sales_pred (pred_date, prod_id, pred_sum) values ('2016-03-25', '2271145', 100);
insert into sales_pred (pred_date, prod_id, pred_sum) values ('2016-04-25', '2271146', 93.31);
insert into sales_pred (pred_date, prod_id, pred_sum) values ('2016-05-25', '2271147', 103.31);
insert into sales_pred (pred_date, prod_id, pred_sum) values ('2016-07-25', '2271148', 73.31);
create table product (prod_id varchar(30), name varchar(30), price float);
insert into product (prod_id, name, price) values ('2271145', 'phone', 3);
insert into product (prod_id, name, price) values ('2271147', 'laptop', 4);
insert into product (prod_id, name, price) values ('2271148', 'PC', 5);
insert into product (prod_id, name, price) values ('2271146', 'mouse', 2);
insert into product (prod_id, name, price) values ('2271149', 'airpods', 7);
As per your condition deviation can be negative so use simply subtract and use colaesce() for converting NULL values to 0(zero).
-- MySQL
SELECT YEAR(sf.fact_date) year
, MONTH(sf.fact_date) month
, p.name
, COALESCE(ROUND(SUM(sf.fact_sum), 2), 0) fact
, COALESCE(ROUND(SUM(slp.pred_sum), 2), 0) Prediction
, ROUND(COALESCE(SUM(slp.pred_sum), 0) - COALESCE(SUM(sf.fact_sum), 0), 2) deviation
FROM sales_fact sf
LEFT JOIN product p
ON sf.prod_id = p.prod_id
LEFT JOIN sales_pred slp
ON slp.prod_id = p.prod_id
AND slp.pred_date = sf.fact_date
GROUP BY YEAR(sf.fact_date), MONTH(sf.fact_date), p.name;
Please check from url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=a9e9f21dd36400d8830a4734aa7ffb29
I have a table name order_history where I store both old_status and new_status of company orders.
the schema of table :
CREATE TABLE order_history (
id int(11) NOT NULL AUTO_INCREMENT,
old_status longtext COLLATE utf8_unicode_ci,
new_status longtext COLLATE utf8_unicode_ci,
created_at datetime NOT NULL,
order_id int(11) DEFAULT NULL,
PRIMARY KEY (id)
}
The insert to populate is :
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (1, '56', '714', '2020-12-20 21:37:54', 94471496);
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (2, '714', '61', '2020-12-20 21:37:56', 94471496);
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (3, '61', '713', '2020-12-20 21:38:17', 94471496);
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (4, '713', '42', '2020-12-20 21:38:26', 94471496);
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (5, '42', '51', '2020-12-20 21:59:17', 94471496);
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (6, '56', '714', '2020-12-20 22:21:27', 94471496);
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (7, '714', '61', '2020-12-20 22:21:29', 94471496);
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (8, '61', '713', '2020-12-20 22:24:28', 94471496);
INSERT INTO order_history (id, old_status, new_status, created_at, order_id) VALUES (9, '713', '42', '2020-12-20 22:24:43', 94471496);
And Now the question I want to find the TIMEDIFF of created_ats between rows that new_status=61 and rows that new_status=42 and old_status=713.
So in the example the affected rows should be (2,4,7,9) , and the right answer will be the TIMEDIFF between rows with ids (2,4) and rows with ids (7,9). But my query returns 3 results instead of 2 and it also calculate the TIMEDIFF between rows (2,9).
How can I exclude this result?
Here is my query:
select *
from (select oschStart.order_id as order_id, TIMEDIFF(oschEnd.created_at, oschStart.created_at) as confirm_time
from (select osch1.order_id, osch1.created_at
from order_history osch1
where osch1.old_status = 713
and osch1.new_status = 42
) oschEnd
join (select osch1.order_id, osch1.created_at
from order_history osch1
where osch1.new_status = 61
) oschStart
on oschStart.order_id = oschEnd.order_id and oschEnd.created_at > oschStart.created_at) order_time;
A simpler approach is to use a correlated sub query
select *,
timediff(
(select created_at from order_history oh1
where oh1.order_id = oh.order_id and
oh1.id > oh.id and
oh1.old_status = '713' and oh1.new_status = '42'
order by oh1.id asc limit 1),oh.created_at) diff
from order_history oh
where new_status = 61;
Why you have the unwanted results?
oschStart will result rows[2,7] and oschEnd will result rows [4,9]. Joining these subqueries will result in 4 rows [(2,4),(2,9),(7,4),(7,9)]. Your condition (on oschStart.order_id = oschEnd.order_id and oschEnd.created_at > oschStart.created_at) will result in these three rows: [(2,4),(2,9),(7,9)]. It wont prune (2,9) because also 9[created_date] > 2[created_date]. So your query will match a oschStart with all oschEnds that occurs after it. But You need it to be matched with the first occurring oschEnd
Solution
Use group by. If you group by your query results on a field and put other fields on your select part, Mysql will fill those fields with first row of that "group". So assuming that order_history is sorted on created_date you may use this query:
select order_time.id , order_time.*
from (
select oschStart.id as id, oschStart.order_id as order_id,
TIMEDIFF(oschEnd.created_at, oschStart.created_at) as confirm_time
from (select osch1.order_id, osch1.created_at
from order_history osch1
where osch1.old_status = 713
and osch1.new_status = 42
) oschEnd
join (select osch1.id as id, osch1.order_id, osch1.created_at
from order_history osch1
where osch1.new_status = 61
) oschStart
on oschStart.order_id = oschEnd.order_id
and oschEnd.created_at > oschStart.created_at)
order_time
group by order_time.id;