ORACLE Query occurrence for an element - mysql

I'll try to explain with a generic example:
I have a table in MySQL with two columns: "Product" and "Client". For each product a client buy, a register is generated in this table.
Now I took 2 products, Stove and Refrigerator, and I want to find the client that bought both products and just them.
In this case, the expected result would be Marley, and why not Maria too? Because beyond the stove and refrigerator she also bought a chair.
How could be a MySQL ORACLE select query to give me that result?
edit: the question was wrong, it's Oracle and not MySQL, thanks Gordon Linoff

You can use aggregation. Assuming there are no duplicates in the table:
select client
from t
group by client
having sum( product in ('Stove', 'Refrigerator') ) = 2 and
count(*) = 2;
If there are duplicates, the logic is:
select client
from t
group by client
having count(distinct case when product in ('Stove', 'Refrigerator') then product end ) = 2 and
count(distinct product) = 2;

Concept Used:
Filter record for Stove and Refrigerator.
Group records by Client
Each Client should have exactly two distinct records, if yes then it should be in result set.
SELECT Client
FROM table
WHERE Product IN ('Stove', 'Refrigerator')
GROUP BY Client
HAVING COUNT(DISTINCT Product) = 2

Related

How can i get a specific data from my dataset using SQL and PHPmyadmin?

I'm new to sql.
I have 3 datasets ,
patient (columns : id age Zip_Code, size, weight, sex)
blood_tests (columns : test_ID, test_date, blood_sugar, laboratory_ID, patient_ID)
laboratory (columns : id, name, Zip_code, departments)
how can i get the number of patients per center ?
i did this code but it doesnt give the number per
select DISTINCT patient_ID, laboratory_ID from patient,blood_tests where patient.id = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id;
but i don't know how to get the total number of patients per center, because some of them did more than one exam in the same center and they have done tests in many labs?
For the second question. he aks us to get the 4 tests that a specific patient carried out in a laboratory called 'NWB'.
and i did this and noticed that he is patient with and ID = 25 but how can i get that without specifying that the id is 25.
select patient_ID, laboratory.name from patient, blood_tests,laboratory where patient_ID = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id HAVING laboratory.name = "NWB";
Thank You in advance.
This query will give you the number of distinct patients that had a blood test done for each laboratory. The query GROUPs all the records with the same laboratory_ID and then counts the number of DISTINCT patients per GROUP. Distinct in this case means that each patient is only counted once per GROUP even if there are multiple records with the same patient_ID and laboratory_ID. However the patient can still be counted in other GROUPs.
SELECT laboratory_ID, COUNT(DISTINCT patient_ID)
FROM blood_tests
GROUP BY laboratory_ID;
You could join the laboratory table to show the name of the laboratory instead of the id.
SELECT laboratory.nom, COUNT(DISTINCT blood_tests.patient_ID)
FROM blood_tests
JOIN laboratory ON laboratory.id = blood_tests.laboratory_ID
GROUP BY blood_tests.laboratory_ID;
Your other question is confusing because there is no 'the' test for a patient having carried out 4 tests. There would be 4 tests - which one of them is 'the' test.
Here is a query that will list the ids of all patients that have had 4 test carried out at the laboratory with the id 42.
SELECT patient_ID
FROM blood_tests
WHERE laboratory_ID = 42
GROUP BY patient_ID
HAVING COUNT(patient_ID) = 4;
EDIT based on comment from OP:
I hope this is useful for anyone trying to learn how to query a database.
When you query a database your asking it for information based on what is found in the database not based on what you already know to be true. You first need to figure out what it is that you are asking.
If you say you know that there is some (some means at least one) specific patient that did exactly 4 tests at laboratory NWB, you could ask the database to list all patients that carried out exactly 4 tests at laboratory NWB.
If you know the specific patient and want to get the tests then you would ask the database for all the tests carried out at at laboratory NWB for this specific patient. In this case the fact that you know there are 4 of them is not a criteria for selection, so it wouldn't appear in your query.
If you know there is some patient that did exactly 4 tests and you want to get their tests. What are you asking the database? You could ask: Find me all tests for any patient that has done exactly 4 tests at laboratory NWB. But if there are other patients that also had exactly 4 tests at that laboratory you would get their tests as well.
Above you saw how to group records together by a criteria and how to count the members of each group.
The HAVING clause allows you to limit results based on criteria that applies to a group.
The WHERE clause allows you to limit results based on criteria that applies to a record.
You should be able to construct a query for any of those scenarios using what was shown above.
You need to use COUNT(DISTINCT ~ ) and GROUP BY. We don't need to use the table patients because we have patient_ID in blood_tests.
SELECT
COUNT( DISTINCT bt.patient_ID) number_patients ,
bt.laboratory_ID
FROM
blood_tests bt
JOIN
laboratory l
ON bt.laboratory_ID = l.id
GROUP BY
laboratory_ID;
For the second request:
SELECT
GROUP_CONCAT(
bt.test_ID
SEPARATOR CHAR(10)
) test_IDs,
bt.patient_ID patientID,
bt.laboratory_ID. labo_ID,
l.name lab_name,
l.Zip_code. lab_zip,
l.departments. lab_dept
FROM
blood_tests bt
JOIN
laboratory l
ON
bt.laboratory_ID = l.id
WHERE
l.name = 'NWB'
GROUP BY
bt.patient_ID ,
bt.laboratory_ID,
l.name lab_name,
l.Zip_code,
l.departments
HAVING
COUNT(bt.test_ID) = 4;
Assuming you're using Mysql with PhpMyAdmin (from now i'll call it PMA)
You get the COUNT of patients for each laboratory using GROUP BY keyword.
You can read the (unofficial) documentation here.
Using GROUP BY you can get the count of tests for each laboratory with
SELECT laboratory_ID, COUNT(*) As num_tests FROM blood_tests WHERE 1 GROUP BY laboratory_ID;
So the query returns 2 columns one for the laboratory ID and one for the number of tests for that one.
You can see the zip code of laboratory using JOINS statements, in this case you should use INNER JOIN click here for (unofficial) documentation

MYSQL query to Select the first duplicate record in JAVA

I am trying to retrieve the the first row among the duplicate row, THE FIRST OCCURED ***
--Table--
Order_No Product User
1 Book Student
2 Book Student
3 Book Student
I want to get the Order_No of the first duplicate row in JAVA, I have used DISTINCT and DISTINCT TOP 1 etc but nothing worked, NEED HELP
SELECT min(order_no), product, user
FROM 'table'
GROUP BY user, product
This is basic SQL?
SELECT min(order_no), product, user FROM table GROUP BY product, user
See also more information on GROUP BY
All fields not part of your group by must have some sort of way to determine which to pick of the n potentially different values. min() will pick the lowest value (even with strings and dates) while max() will pick the highest. You can also use First() and Last() to grab the value according to when they show up.
Supposing you had other values to pick from, you might see something like:
SELECT min(order_no), product, user, min(creation_date),
sum(quantity), first(billing_address)
FROM orders GROUP BY product, user
SELECT t.*
FROM table t
WHERE NOT EXISTS ( SELECT a
FROM table t2
WHERE t2.Product = t.Product
AND t2.User = t.User
AND t2.Order_No < t.Order_No
)

count number of repeating entries

I am fairly new to Databases and I am just beginning to understand the DML/queries, I have two tables, one named customer this contain customer data and one named requested_games, this contains games requested by the customers, I would like to write a query that will return the customers that have requested more than two games, so far when I run the query, I don't get the desired result, not sure if I'm doing it right.
Can anyone assist with this thanks,
Below is a snippet of the query
select customers.customer_name, wants_list.requested_game, wants_list.wantslists_id,count(wants_list.customers_ID)
from customers, wants_list
where customers.customers_ID = wants_list.customers_id
and wants_list.wantslists_id = wants_list.wantslists_id
and wants_list.requested_game > '2';
just include a HAVING clause
GROUP BY customers_ID
HAVING COUNT(*) > 2
depending on how you have your data setup you may need to do
HAVING COUNT(wants_list.requested_game) > 2
This is how I like to describe how a query works maybe itll help you visualize how the query executes :)
SELECT is making an order at a restaurant....
FROM is the menu you want to order from....
JOIN is what sections of the menu you want to include
WHERE is any customization you want to make to your order (aka no mushrooms)....
GROUP BY (and anything after) is after the order has been completed and is at your table...
GROUP BY tells your server to bring your types of food together in groups
ORDER BY is saying what dishes you want first (aka i want my entree then dessert then appetizer ).
HAVING can be used to pick out any mushrooms that were accidentally left on the plate....
etc..
I would like to write a query that will return the customers that
have requested more than two games
For this to happen you need to do the following
First you need to use GROUP BY to group the games based on customers (customers_id)
Then you need to use HAVING clause to get customers who requested more than two games
Then make this a SUBQUERY if you need more information on the customer like name
Finally you use a JOIN between customers and the sub query (temp) to display more information on the customer
Like the following query
SELECT customers.customer_id, customers.customer_name, game_count
FROM (SELECT customer_id, count(wantslists_id) AS game_count
FROM wants_list
GROUP BY customer_id
HAVING count(requested_game) > '2') temp
JOIN customers ON customers.customer_id = temp.customer_id

mysql select problem

Hi were trying to perform a mysql select which isnt going to plan and hoping someone can shed some light on it.
we have estimated 10,000 plus listing records, a customer can have several listing records for different locations. we need to select all customer listings where at least one of the locations is equal to a specifield location.
so for example lets say customer 1 has a listing in sheffiled, doncaster, leeds, wakefield and customer 2 has listings in london and brighton.
Now I want to select all customer listings where one of the listings is for the area sheffield.
Id hope to get back the 4 rows for customer 1 because one of his listings is in sheffield.
for the sake of this example lets just presume the table consists of just customerId and LocationName
I need to select all customerIds where one of the locationNames = sheffield. So Id get 4 rows retruend with the cusotmer ID and the 4 locations
How do you write this query in mysql? Im guessing subselect but not too sure.
SELECT customerid FROM customers_location
WHERE customerid IN(SELECT DISTINCT customerid FROM customers_location WHERE LocationName = 'sheffield')
Something like:
SELECT * FROM CUST_TABLE WHERE CUST_ID IN (
SELECT DISTINCT CUST_ID FROM CUST_TABLE WHERE CUST_LOCN='Sheffield')
Note; The distinct clause may not be strictly necessary, not sure.
That would give you eg. 4 records for customer xyz who has one of their listing locations as Sheffield, which I think is what you're asking.

Retrieving specific tuples using Mysql

I have some problems retrieving specific tuples.
I am actually a student trying to build a Room management system. I have two tables:
Room(roomID,hotelname,rate)
and
Reservation(resID,arriveDate,departDate,roomID).
I am not sure how to retrieve the rooms that are available between 2 specific dates.
This was the query that i used.
SELECT Room.roomID,hotelname,rate
FROM Room
LEFT JOIN Reservation
on ( Room.roomID=Reservation.resID
and arriveDate >='2010-02-16'
and departDate <='2010-02-20'
)
GROUP BY roomID,hotelname,rate
HAVING count(*)=0;'
but it returns an empty set. Can any1 be kind enough to tell me what mistake i am doing??
I guess Room.roomID=Reservation.resID should be Room.roomID=Reservation.roomID.
You could try a different approach with a subselect:
SELECT roomID,hotelname,rate
FROM Room
WHERE roomID NOT IN (SELECT roomID FROM Reservation WHERE arriveDate >='2010-02-16' and departDate <='2010-02-20')