MySQL Workbench reports an error Code: 1064 in MySQL - mysql

SELECT OrderID, OrderDate, Freight
FROM orders
WHERE CustomerID IN (SELECT CustomerID FROM WHERE City in ('Germany', 'Mexico', 'Spain'))
ORDER BY Freight DESC;

Your inner SELECT clause has a from with out a table.
I added orders2 as tablename because i don't know exactly what you have in mind
SELECT OrderID, OrderDate, Freight
FROM orders
WHERE CustomerID IN (SELECT CustomerID FROM orders2 WHERE City in ('Germany', 'Mexico', 'Spain'))
ORDER BY Freight DESC;

Question is not clear but if only one table is involved, I think this is a simple form.
SELECT OrderID, OrderDate, Freight
FROM orders
WHERE City IN ('Germany', 'Mexico', 'Spain'))
ORDER BY Freight DESC;
or if there are two tables
SELECT a.OrderID, a.OrderDate, a.Freight
FROM orders a, orders2 b
WHERE a.CustomerID=b.CustomerID AND b.city IN ('Germany', 'Mexico', 'Spain'))
ORDER BY a.Freight DESC;
A join may also be used.

Related

Why this code showing invalid use of group function?

CREATE VIEW SALESMAN_WITH_MAX_ORDER AS
(SELECT S.Salesman_id,
S.Name,
S.City,
Commission
FROM SALESMAN S,
CUSTOMER C
WHERE S.Salesman_id=C.Salesman_id
AND Customer_id IN (SELECT Customer_id
FROM ORDERS
GROUP BY Customer_id,
Ord_Date
HAVING SUM(PURCHASE_AMT) = (SELECT MAX(SUM(PURCHASE_AMT))
FROM ORDERS
GROUP BY Customer_id,
Ord_Date)));
You have a problem in the innermost query. You cannot do a MAX with a SUM as argument.
This is how you would do it in T-SQL, sorry I have no mysql to test it on right now.
CREATE VIEW SALESMAN_WITH_MAX_ORDER AS
(
SELECT S.Salesman_id,
S.Name,
S.City,
Commission
FROM SALESMAN S,
CUSTOMER C
WHERE S.Salesman_id=C.Salesman_id
AND Customer_id IN
(
SELECT Customer_id
FROM ORDERS
GROUP BY Customer_id,Ord_Date
HAVING SUM(PURCHASE_AMT)=
(
SELECT MAX(SUM_AMT)
FROM
(
SELECT SUM(PURCHASE_AMT) AS SUM_AMT
FROM ORDERS
GROUP BY Customer_id,Ord_Date
) innerTableName
)
)
);

How to SELECT customers with orders before specific date

I have two table.
Table 'customers': customer_id, date_register, name
Table 'orders': order_id, customer_id, order_date
Now I want the customers who have orders before specific date and have NOT after that date.
I am using this query:
SELECT customer_id
FROM orders
WHERE EXISTS (SELECT order_id
FROM orders
WHERE order_date <= '2020-05-12 23:59:59')
AND NOT EXISTS (SELECT order_id
FROM orders
WHERE order_date > '2020-05-12 23:59:59')
But I get empty result.
What SQL query should I use?
You can use aggregation and set the condition in the HAVING clause:
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING MAX(order_date) < '2020-05-13';
You could try selecting the customer based on the two range using main query and a subquery in left join then checking for not matching id
SELECT DISTINCT customer_id
FROM orders
LEFT JOIN
(SELECT DISTINCT customer_id
FROM orders
WHERE order_date > '2020-05-12 23:59:59') t ON t.customer_id = orders.customer_id
AND orders.order_date <= '2020-05-12 23:59:59'
WHERE t.id IS NULL

Orders that have not yet been paid mysql

I am stuck with the following problem: I would like to return from my query the orders which have yet to be paid with the amount of the order and my customer information.
Here is what the tables look like:
Taking the case of customer number 124. I can see that this one has placed 13 orders. But I only have 7 checks registered
And I can see that if I add the sum of the orders minus the sum of the payments I find a difference that corresponds to the last 3 orders that this customer has placed.
So the question is how do I bring out the commands 10382, 10371, 10368 with all that? Knowing that the solution must be able to be applied to all orders.
So I thought to myself maybe using the order and payment dates. What orders does my customer place between their last payment and today?
So I tried something like this
#last order date
WITH last_cmd AS
(
SELECT
customerNumber, od.orderNumber, orderDate last_orderDate,
shippedDate, SUM(quantityOrdered * priceEach) totcmd
FROM
orders o
LEFT JOIN
orderdetails od ON o.orderNumber = od.orderNumber
WHERE
status NOT LIKE 'Can%'
GROUP BY
orderDate
ORDER BY
customerNumber, orderDate DESC
),
#last payment date last_payment AS
(
SELECT
customerNumber, amount, paymentDate, checkNumber
FROM
payments
GROUP BY
paymentDate
ORDER BY
customerNumber, paymentDate DESC
)
SELECT *
FROM last_cmd lc
LEFT JOIN last_payment lp ON lc.customerNumber = lp.customerNumber
GROUP BY lc.orderNumber
HAVING MAX(paymentDate) NOT BETWEEN MAX(last_orderDate) AND NOW();
But as you can see the result is not really what is expected. Still taking customer 124 as an example, command 10382 does not appear. And when I do the comparison of other orders manually for other customers the results do not match.
Does anyone have an idea please?
Here is the query I tried before posting
WITH ALL_PAYMENTS AS (
WITH paymentsValues AS (
select customerNumber, checkNumber, YEAR(paymentDate) paymentYear, sum(amount) paymentValue
from payments
LEFT JOIN customers USING (customerNumber)
GROUP BY customerNumber, paymentYear)
SELECT
customerNumber,
checkNumber, #Cumul des commandes clients
paymentYear,
SUM(paymentValue) totalPaymentsValue
FROM
paymentsValues
GROUP BY
customerNumber,
checkNumber
WITH ROLLUP
HAVING checkNumber is null),
ALL_ORDERS AS(
WITH ordersValues AS (
select customerNumber, orderNumber, YEAR(orderDate) orderYear, sum(quantityOrdered*priceEach) AS orderValue
from orderdetails
LEFT JOIN orders USING (orderNumber)
GROUP BY orderNumber, orderYear)
SELECT
customerNumber,
orderNumber, #Cumul des commandes clients
orderYear,
SUM(orderValue) totalOrderValue
FROM
ordersValues
#where orderNumber = '10179'
GROUP BY
customerNumber,
orderNumber
WITH ROLLUP
HAVING orderNumber is null)
SELECT AO.customerNumber, totalOrderValue, totalPaymentsValue, totalOrderValue-totalPaymentsValue Diff
FROM ALL_ORDERS AO
LEFT JOIN ALL_PAYMENTS AP ON AP.customerNumber=AO.customerNumber
WHERE totalOrderValue-totalPaymentsValue > 0;
This should give a list op amount that have to be paid, per date:
WITH d as (
select distinct orderDate as `date` from orders
union
select distinct paymentDate as `date` from payments)
select
`date`,
`customerNumber`,
`ordersValue`,
`amountPayed`,
`ordersValue` - `amountPayed` NotPayed
from (
select
d.`date` as "date",
o.customerNumber as "customerNumber",
sum(quantityOrders*priceEach) ordersValue,
(select sum(amount)
from payments p
where o.customerNumber = p.customerNumber AND p.paymentDate <= d.`date`) as amountPayed
from orderdetails od
cross join d
inner join Orders o on od.orderNumber = o.orderNumber AND o.orderDate <= d.`date`
group by d.`date`, o.customerNumber
) orderListPerCustomer
WHERE `customerNumber` = 124
ORDER BY `date` DESC
;
It is impossible to add order info, because there is no order info in the payments
This query does not take into account the status of the order (which might be Cancelled)
NOTE: This code is not tested, so there could be typing errors...

Subquery repeats values

I got this query to retrieve total price, average and difference but i think i am inputting the group by or order by incorrect because it shows me all the data i want except it just repeats the same customer name, cellphone and email for every result but the total price, average and difference are all different
SELECT
FirstName,
LastName,
CellPhone,
Email,
TotalPrice,
AVG(TotalPrice) AS 'Average Total Price',
TotalPrice - 'Average Total Price' AS 'Difference Total Price'
FROM
customer,
(SELECT
CID, TotalPrice
FROM
orders) AS c
GROUP BY TotalPrice
ORDER BY FirstName;
I suspect this is what you want:
SELECT
c.FirstName,
c.LastName,
c.CellPhone,
c.Email,
o.TotalPrice,
a.AvgPrice AS `Average Total Price`,
o.TotalPrice - a.AvgPrice AS `Difference Total Price`
FROM customer AS c
JOIN orders AS o ON c.ID = o.CID
JOIN (
SELECT CID, AVG(TotalPrice) AS AvgPrice
FROM orders
GROUP BY CID
) AS a ON a.CID = c.ID
ORDER BY c.FirstName
The subquery gets the average totals from all the orders of each customer. This is then joined with the rows for each order so you can get the difference.

MySQL Sum from Alias Table

I have this query...
CREATE VIEW CustOrderItems AS
SELECT CustFirstName, CustLastName, OrderNumber, OrderDate, ShipDate,
QuantityOrdered * QuotedPrice AS ItemTotal
FROM Customers NATURAL JOIN Orders NATURAL JOIN Order_Details;
After grouping the orders like this...
SELECT CustFirstName, CustLastName, OrderNumber, OrderDate, ShipDate,
QuantityOrdered * QuotedPrice AS ItemTotal
FROM Customers NATURAL JOIN Orders NATURAL JOIN Order_Details
GROUP BY OrderNumber
ORDER BY OrderNumber ASC;
I know need to calculate the sum of all the ItemTotal's added together?
Any help is much appreciated!
As has been mentioned in a comment already, you get sums in SQL with SUM, which should not be much of a surprise. It seems strange you know about GROUP BY, but not about SUM.
At this point I'd like to recommend to always aggregate before joining, not afterwards. You want orders with their customer information and their total price. So select from orders, join with customers, join with total prices. Once you want aggregates from different tables, this approach will save you some trouble.
SELECT
c.CustFirstName,
c.CustLastName,
o.OrderNumber,
o.OrderDate,
o.ShipDate,
od.OrderTotal
FROM Orders o
JOIN Customers c ON c.CustomerNumber = o.CustomerNumber
JOIN
(
SELECT
OrderNumber,
SUM(QuantityOrdered * QuotedPrice) AS OrderTotal
FROM Order_Details
GROUP BY OrderNumber
) od ON od.OrderNumber = o.OrderNumber
ORDER BY o.OrderNumber ASC;