SQL Plus Error At Line 1 - mysql

I need to list each order, list the order ID, order date, customer ID, customer first name, customer last name, sales rep ID, sales rep first name, and sales rep last name; sort by order ID; Format the order date as “mm/dd/yy”.
Here is my UPDATED Code!
SELECT Order_ID as Order_ID, to_char(Order_Date, 'mm/dd/yyyy') as Date, OR.Cust_ID as Cust_ID,
Cust_FName as Cust_FName, Cust_LName as Cust_LName, SR.Sales_Rep_ID as Sales_Rep_ID,
Sales_Rep_FName as Sales_Rep_FName, Sales_Rep_LName as SalesRepLName
FROM ORDER_arb OR, CUSTOMER_arb C, SALES_REP_arb SR
WHERE OR.Cust_ID = C.Cust_ID AND
C.Sales_Rep_ID = SR.Sales_Rep_ID
ORDER BY Order_ID;
I am receiving this error:
UPDATE!!
Error at Line 1: FROM keyword not found where expected
I would appreciate any input.
Thanks

Try this. Please change 'OR' to 'ORD' and 'as Date' to 'as OrderDate'.
Because DATE is a keyword in oracle. and OR alias seems working different than wen think. If you still needs to use column alias sa Date, please use with double quotes as "Date"
SELECT ORD.Order_ID as Order_ID, to_char(ORD.Order_Date, 'mm/dd/yyyy') as OrderDate, ORD.Cust_ID as Cust_ID,
C.Cust_FName as Cust_FName, C.Cust_LName as Cust_LName, SR.Sales_Rep_ID as Sales_Rep_ID,
SR.Sales_Rep_FName as Sales_Rep_FName, SR.Sales_Rep_LName as SalesRepLName
FROM ORDER_arb ORD, CUSTOMER_arb C, SALES_REP_arb SR
WHERE ORD.Cust_ID = C.Cust_ID
AND C.Sales_Rep_ID = SR.Sales_Rep_ID
ORDER BY Order_ID;

Related

SQL Group by returning wrong results

I have a salary table in which I am trying to return determine the lowest salary earned and by which industry for each year however despite getting the correct lowest salary earned I am receiving the wrong industry name.
I am aware that it is due to the fact that I have utilized GROUP BY without placing a constraint(?) on it hence it is returning me the wrong value but I am not sure how I can solve it.
SALARY TABLE
salaryID
salaryAmount
salaryYear
industryName (ForeignKey)
Can someone please guide me on the right path?
**(Problem Code)**
SELECT MIN(S.salary), S.industryName, S.salaryYear
FROM salary
GROUP BY S.salaryYear;
**(Attempted solution)**
SELECT S.salary
FROM salary
INNER JOIN
SELECT (min(S1.amount)), S1.year, S1.industryName, S1.salaryId
FROM salary S1
GROUP BY S1.year
ON S.salaryId = S1.salaryId);
Use a proper GROUP BY. Any non-aggregated columns must be included in GROUP BY.
SELECT MIN(amount), year
FROM salary
GROUP BY year
If you want to include industryName,
SELECT amount, year, industryName, salaryId
FROM (
SELECT amount, year, industryName, salaryId
, ROW_NUMBER() OVER(PARTITION BY year ORDER BY amount) AS rn
FROM salary
) a
WHERE rn = 1
Pre-MySQL 8 version
SELECT *
FROM salary s
INNER JOIN (
SELECT MIN(amount) AS minAmount, year
FROM salary
GROUP BY year
) m ON m.minAmount = s.amount AND m.year = s.year
I think you need a self-join :
SELECT s1.industryName, s2.min_salary, s2.salaryYear
FROM salary s1
JOIN
(
SELECT MIN(salary) as min_salary, salaryYear
FROM salary
GROUP BY salaryYear
) s2
ON s1.salary = s2.min_salary
AND s1.salaryYear = s2.salaryYear;
The Demo of this query with your sample data

Coalesce with Roll Up not working correctly (MySql)

I am trying to coalesce on the roll up (against the year revenue), The roll up is calculating correctly, however instead of inputting 'Grand Total' at the end of the table, 'Socks' is being inputted again.
Any ideas what i am doing wrong?
select coalesce(product_name, 'total') as product_name, sum(price) as year_revenue
from orders
join product on orders.ProductID = product.ProductID
group by month(order_data) with rollup;
'Blue Shirt', '69.93'
'Denim Jeans', '197.91'
'White Blazer', '94.97'
'Socks', '109.94'
'Skinny Jeans', '73.96'
'Mini Skirt', '31.98'
'White Blazer', '74.97'
'Black Blazer', '40.99'
'Shorts', '19.98'
'Mini Skirt', '85.96'
'Flare Blouse', '33.98'
'Socks', '7.98'
'Socks', '842.55'
The reason for this is that you are grouping by MONTH(order_data), not product_name. When WITH ROLLUP happens, it is the grouped by column value that gets replaced by NULL. If you were to change your query to:
SELECT MONTH(order_data) AS month, product_name, SUM(price) AS year_revenue
FROM orders
JOIN product ON orders.ProductID = product.ProductID
GROUP BY month WITH ROLLUP
You would see the NULL values in the month column.
To achieve what you want, try changing your query to this:
SELECT IF(month IS NULL, 'Total', product_name) AS product_name, year_revenue
FROM (SELECT MONTH(order_data) as month, product_name, SUM(price) AS year_revenue
FROM orders
JOIN product ON orders.ProductID = product.ProductID
GROUP BY month WITH ROLLUP)

Most frequent value + number of time displayed in columns for each

I've got the following order table:
Client_name|Product Megane|#768_Samsung Megane|#310_Apple
Megane|#659_Samsung Victor|#890_Apple
I'd like to see for each client what's their most bought brand + the number of time they bought it.
So for this table, I'd like this result:
Client_Name|Favourite_brand|Order_number Megan|Samsung|2
Victor|Apple|1
So far this is the query I've built:
SELECT Client_name, brand
FROM (SELECT Client_name, brand, ROW_NUMBER() OVER (PARTITION BY Client_name ORDER BY freq DESC) AS rn
FROM ( SELECT Client_name, brand, COUNT('x') AS freq
FROM (SELECT Client_name, substring(Product,5) as brand
FROM Orders
GROUP BY Client_name, brand) frequency) ranked) client
WHERE rn = 1;
I am still struggling with removing the number before the brand name (ie #768 for instance) by using substring. I shows me an error message
-ERROR: column "frequency.Client_name" must appear in the GROUP BY clause or be used in an aggregate function
So I haven't started yet to think how to add the Order_number column
Your help is highly appreciated!
I think you just have your group by clause in the wrong spot. Try moving it to after the 'frequency' but before the ')'
SELECT Client_name, brand
FROM (SELECT Client_name, brand, ROW_NUMBER() OVER (PARTITION BY Client_name ORDER BY freq DESC) AS rn
FROM ( SELECT Client_name, brand, COUNT('x') AS freq
FROM (SELECT Client_name, substring(Product,5) as brand
FROM Orders) frequency GROUP BY Client_name, brand) ranked) client
WHERE rn = 1;

MySQL query (CustomerID and dates of 1st, 2nd and 3rd purchases)

I am trying to create a dashboard with customer ID and dates of 1st, 2nd and 3rd purchases. I use MySQL, Northwind db.
My query works perfectly fine for the 1st purchase, but I do not understand how to find 2nd and 3rd purchase date for each customer.
Now I'm trying to do next: 2nd_purchase_date is the next MIN(OrderDate) after 1st_purchase_date but I get following error 'Invalid use of group function'
DROP TABLE IF EXISTS t1;
CREATE TABLE t1
(
CustomerID varchar(5),
OrderDate datetime,
OrderID int,
i int
);
INSERT INTO t1(CustomerID, OrderDate, OrderID, i)
SELECT CustomerID, min(OrderDate), min(OrderID),1
FROM Orders
GROUP BY CustomerID;
INSERT INTO t1(CustomerID, OrderDate, OrderID, i)
SELECT CustomerID,min(OrderDate), min(OrderID),2
FROM Orders
WHERE min(OrderDate)
NOT IN
(
SELECT CustomerID, min(OrderDate), min(OrderID)
FROM Orders
)
GROUP BY CustomerID;
INSERT INTO t1(CustomerID, OrderDate, OrderID, i)
SELECT CustomerID,min(OrderDate), OrderID,3
FROM Orders
WHERE min(OrderDate)
NOT IN
(
SELECT CustomerID, min(OrderDate), min(OrderID) FROM Orders
)
GROUP BY CustomerID;
As shown in the last example here, you can use the LIMIT offset, count feature in combination with ORDER BY column ASC to select the entry with the second purchase date for a single user (with the id XXX replaced with the respective value):
SELECT CustomerID, OrderDate, OrderID
FROM Orders
WHERE CustomerID = XXX
ORDER BY OrderDate ASC
LIMIT 1, 1;
or the entry with the third purchase date:
SELECT CustomerID, OrderDate, OrderID
FROM Orders
WHERE CustomerID = XXX
ORDER BY OrderDate ASC
LIMIT 2, 1;
... and so on.
You get the first entry via
SELECT CustomerID, OrderDate, OrderID
FROM Orders
WHERE CustomerID = XXX
ORDER BY OrderDate ASC
LIMIT 0, 1;
or the equivalent:
SELECT CustomerID, OrderDate, OrderID
FROM Orders
WHERE CustomerID = XXX
ORDER BY OrderDate ASC
LIMIT 1;
This should give you the first three orders for a single customer:
SELECT CustomerID, OrderDate, OrderID
FROM Orders
WHERE CustomerID = XXX
ORDER BY OrderDate ASC
LIMIT 3;
While the following is definitely not good from a performance perspective, it should still work to give you the first three orders for each customer:
SELECT o1.CustomerID, o1.OrderDate, o1.OrderID
FROM Orders o1
WHERE o1.OrderID IN
(SELECT o2.OrderID
FROM Orders o2
WHERE o1.CustomerID = o2.CustomerID
ORDER BY o2.OrderDate ASC LIMIT 3)
ORDER BY o1.CustomerID, o2.OrderDate ASC;

making a query for stock/price trend in mysql

SQL Fiddle
Table scheme:
CREATE TABLE company
(`company_id` int,`name` varchar(30))
;
INSERT INTO company
(`company_id`,`name`)
VALUES
(1,"Company A"),
(2,"Company B")
;
CREATE TABLE price
(`company_id` int,`price` int,`time` timestamp)
;
INSERT INTO price
(`company_id`,`price`,`time`)
VALUES
(1,50,'2015-02-21 02:34:40'),
(2,60,'2015-02-21 02:35:40'),
(1,70,'2015-02-21 05:34:40'),
(2,120,'2015-02-21 05:35:40'),
(1,150,'2015-02-22 02:34:40'),
(2,130,'2015-02-22 02:35:40'),
(1,170,'2015-02-22 05:34:40'),
(2,190,'2015-02-22 05:35:40')
I'm using Cron Jobs to fetch company prices. In concatenating the price history for each company, how can I make sure that only the last one in each day is included? In this case, I want all of the price records around 05:30am concatenated.
This is the result I'm trying to get (I have used Date(time) to only get the dates from the timestamps):
COMPANY_ID PRICE TIME
1 70|170 2015-02-21|2015-02-22
2 120|190 2015-02-21|2015-02-22
I have tried the following query but it doesn't work. The prices don't correspond to the dates and I don't know how to exclude all of the 2:30 am records before applying the Group_concat function.
SELECT company_id,price,trend_date FROM
(
SELECT company_id, GROUP_CONCAT(price SEPARATOR'|') AS price,
GROUP_CONCAT(trend_date SEPARATOR'|') AS trend_date
FROM
(
SELECT company_id,price,
DATE(time) AS trend_date
FROM price
ORDER BY time ASC
)x1
GROUP BY company_id
)t1
Can anyone show me how to get the desired result?
Ok, so this should work as intended:
SELECT p.company_id,
GROUP_CONCAT(price SEPARATOR '|') as price,
GROUP_CONCAT(PriceDate SEPARATOR '|') as trend_date
FROM price as p
INNER JOIN (SELECT company_id,
DATE(`time`) as PriceDate,
MAX(`time`) as MaxTime
FROM price
GROUP BY company_id,
DATE(`time`)) as t
ON p.company_id = t.company_id
AND p.`time` = t.MaxTime
GROUP BY p.company_id
Here is the modified sqlfiddle.
This is a bit unorthodox but I think it solves your problem:
SELECT company_id,
GROUP_CONCAT(price SEPARATOR'|'),
GROUP_CONCAT(trend_date SEPARATOR'|')
FROM (
SELECT *
FROM (
SELECT company_id,
DATE(`time`) `trend_date`,
price
FROM price
ORDER BY `time` DESC
) AS a
GROUP BY company_id, `trend_date`
) AS b
GROUP BY company_id