SELECT SUM(FieldName) FROM TableName between Column_Value and Column_Value; - mysql

Everyone. I have SQL Query Questions.
can I calculate the values between two columns.?
for. example. I have a table Book;
CREATE TABLE Book(
ID int,
DateOfSellBook Date,
Book varchar(255),
SellBook int (255),
);
INSERT INTO `book`(`ID`, `Date`, `Book Title`, `Sell Book`) VALUES (1, 3/2/2021, Java,10);
INSERT INTO `book`(`ID`, `Date`, `Book Title`, `Sell Book`) VALUES (2,3/3/2021,Java,10);
INSERT INTO `book`(`ID`, `Date`, `Book Title`, `Sell Book`) VALUES (3,3/4/2021,javascript,10);
INSERT INTO `book`(`ID`, `Date`, `Book Title`, `Sell Book`) VALUES (4,3/5/2021,php,10);
between ID 1 and 3, How Many Books Sell ?.
SELECT SUM(FieldName) FROM TableName between Column_Value and Column_Value; but it's not working for me please help

Try this:
SELECT count(distinct book_number) FROM book
where id between 1 and 4
This query will give you list of unique book_number between id 1 and 4. To get all the book_number (if there is a book named 'book a' two times then it will be counted two times):
SELECT count(book_number) FROM book
where id between 1 and 4

Related

Extract only rows with highest values

I am relatively new to SQL and I am trying to extract rows where they have the highest values.
For example, the table look like this:
user_id fruits
1 apple
1 orange
2 apple
1 pear
I would like to extract the data such that it would look like this:
user_id fruits
1 3
If user_id 2 has 3 fruits, it should display:
user_id fruits
1 3
2 3
I can only manage to get the if I use LIMIT = 1 by DESC order, but that is not the right way to do it. Otherwise I am getting only:
user_id fruits
1 3
2 1
Not sure where to store the max value to put in the where clause. Appreciate any help, thank you
Use RANK():
WITH cte AS (
SELECT user_id, COUNT(*) AS cnt, RANK() OVER (ORDER BY COUNT(*) DESC) rnk
FROM yourTable
GROUP BY user_id
)
SELECT user_id, cnt AS fruits
FROM cte
WHERE rnk = 1;
Here's one answer (with sample data):
CREATE TABLE something (user_id INT NOT NULL, fruits VARCHAR(10) NOT NULL, PRIMARY KEY (user_id, fruits));
INSERT INTO something VALUES (1, 'apple');
INSERT INTO something VALUES (1, 'orange');
INSERT INTO something VALUES (2, 'apple');
INSERT INTO something VALUES (1, 'pear');
INSERT INTO something VALUES (2, 'orange');
INSERT INTO something VALUES (2, 'pear');
SELECT user_id, COUNT(*) AS cnt
FROM something
GROUP BY user_id
HAVING COUNT(*) >= ALL (SELECT COUNT(*) FROM something GROUP BY user_id);

Insert multiple rows in a table using a subquery

I'm trying to get all the items of the cart_items and add it to the ticket_items.
I've the error "SUBQUERY RETURN MULTIPLE ROWS", but that's what I want, insert all that rows in the ticket_items table in a same query.
INSERT INTO ticket_items (ticket_id, ISBN, quantity)
VALUES (
(SELECT COUNT(ticket_id) FROM ticket),
(SELECT ISBN FROM cart_items WHERE customer_id = 1),
(SELECT quantity FROM cart_items WHERE customer_id = 1)
);
The issue is that you are using an aggregate function (COUNT) that will build exactly one value, but both isbn and quantity occur twice or more. So, the insert that will be built by your query is something like
INSERT INTO ticket_items (ticket_id, ISBN, quantity)
VALUES (10, 1,2,3, 4,5,6);
This is of course not allowed. Since you do a COUNT, you need to apply GROUP BY to create multiple rows which will be inserted.
So your insert command will be something like this:
INSERT INTO ticket_items (ticket_id, ISBN, quantity)
((SELECT COUNT(ticket_id), ISBN, quantity
FROM ticket, cart_items
WHERE customer_id = 1
GROUP BY ISBN, quantity));
This will work correctly and do what you asked for, I created an example here: db<>fiddle
You should check if this is really what you want because for me, it doesn't make sense to insert the count of ticket_id like you describe. But this is something you must check on your own.
Don't use VALUES keyword.
Please see syntax below:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
I would first make sure that select gives you the expected result, then issue the insert statement.
Upon review, I believe the issue is with SELECT part.
You should rewrite it as one SELECT:
INSERT INTO ticket_items (ticket_id, ISBN, quantity)
(SELECT
(SELECT COUNT(ticket_id) from ticket) as ticket_id, ISBN, quantity
FROM cart_items
WHERE customer_id = 1)
Good luck!

Mysql query to find IDs from a list that don't exist in a table

I'm trying to execute mysql query to find ids that dont exist in table but I'm getting an error. What am I doing wrong? Here is my query
create table scientist (id integer , firstname varchar(100), lastname varchar(100));
insert into scientist (id, firstname, lastname) values (1, 'albert', 'einstein');
insert into scientist (id, firstname, lastname) values (2, 'isaac', 'newton');
insert into scientist (id, firstname, lastname) values (3, 'marie', 'curie');
select * from (
VALUES ROW (1 , 2 , 3, 4, 5)
) as V
WHERE id not EXIST (select id from scientist);
I expect to see 4 and 5 in output
You would use not exists like this:
select *
from (VALUES ROW (1) , ROW (2) , ROW (3), ROW (4), ROW (5)
) v(id)
where not exists (select 1 from scientist s where s.id = v.id);

How to find a record that does not exists from a table based on other table value

So i have two tables, this one is books
and this one is payment
now i want to select if there are any records in books that have a similiar(select * from a like a.field like '%blabla%) title or even the same title but not exist in payment
i tried not exist but im not sure because the executing query process is very long so i thought it wasn't the case.
Given the information, I have tried to put together an example. I hope this is helpful and gets you close to what you want.
CREATE TABLE books
(`number` int, `verification_date` date, `title` varchar(6))
;
INSERT INTO books
(`number`, `verification_date`, `title`)
VALUES
(14116299, '2020-05-01 18:00:00', 'Title1'),
(12331189, '2020-07-01 18:00:00', 'Title2'),
(13123321, NULL, 'Title4'),
(12318283, '2020-12-31 18:00:00', 'Title3'),
(12318284, '2021-01-31 18:00:00', 'Title2')
;
CREATE TABLE payments
(`number` int, `title` varchar(6), `pay_date` date)
;
INSERT INTO payments
(`number`, `title`, `pay_date`)
VALUES
(14116299, 'Title1', '2020-05-01 18:00:00'),
(12318283, 'Title3', '2020-12-31 17:00:00')
;
We are selecting all columns from books and keeping only records that don't have a match in the payments table. More info on this: How to select rows with no matching entry in another table?. Then added an additional where clause to search the books table for titles.
SELECT b.*
FROM books b
LEFT JOIN payments p ON b.number = p.number
WHERE p.number is NULL
AND b.title LIKE'%2'
Output:
number verification_date title
12331189 2020-07-01 Title2
12318284 2021-01-31 Title2
SQL Fiddle

MySQL Select duplicates with LEAST condition

I'm trying to find duplicates and select the result with the least value combination in a table.
Until now I'm only able to select the result that has the lowest value on a column using MIN(). I thought it would be easy to just replace MIN with LEAST and change the columns.
Here's a layout:
CREATE TABLE `index`.`products` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(10) NOT NULL , `price` INT NOT NULL , `availability` INT NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
INSERT INTO `products` (`id`, `name`, `price`, `availability`) VALUES
(NULL, 'teste', '10', '1'),
(NULL, 'teste', '5', '2'),
(NULL, 'teste', '3', '3');
The simplified layout
id - name - price - availabilty
1 - test - 10 - 1
2 - test - 5 - 2
3 - test - 3 - 3
using the following query:
select name, MIN(price) from products group by name having count(*) > 1
gets me the lowest price. I'm trying to get the lowest price and lowest availabilty.
select name, LEAST(price, availability) from products group by name having count(*) > 1
This doesn't work.
Clarification: I want to select the row with the lowest price and lowest availabity. In this case it should be the first one I guess.
I should clarifity that 1=available, 2=not available and 3=coming soon
The statement to select lowest price for the best availability is:
set sql_mode=only_full_group_by;
SELECT
name, MIN(price), availability
FROM
products
JOIN
(
SELECT
name, MIN(availability) availability
FROM
products
GROUP BY name
) as x
USING (name , availability)
GROUP BY name , availability;