Is there anyway to perform a Count() when using Min()? - mysql

The statement below is to get all non-duplicate IDs from the products table. Is there a way I can get the total count of rows that are outputted by this sql statement?
select min(product_id) from products
where market_code = 'germany'
group by product_code
sample table data:
product_id market_code product_code
1 uk AAA
1 uk AAA
1 uk AAA
2 germany BAA
2 germany BAA
3 uk BAA
Thanks

You can simply do this:
SELECT COUNT(*)
FROM
(
select min(product_id) from products
where market_code = 'germany'
group by product_code
) AS t;

Actually your query is not what you said "The statement below is to get all unique/non-duplicate IDs from the products table." , It will select lowest product_id for product_code , not unique , for example if there are product_id - 2 and product_id - 3 for product_code A , it will only return product_id - 2 , it is a minimum value not unique , if you want unique you could do this way
SELECT product_code,product_id,count(*)
FROM TABLE
GROUP BY product_code,product_id
if you want just unique/non-duplicate ID-s and their count you can select with this query
SELECT product_id,count(*)
FROM table
GROUP BY product_id

The statement:
select min(product_id)
from products
where market_code = 'germany'
group by product_code;
is going to have as many rows as there are product code values in Germany. If you assume that a given product id never has two codes (which is true of your sample data), then the following counts the products in Germany without using product id at all:
select count(distinct product_code)
from products
where market_code = 'germany';

Related

MySQL: Select rows where field contains unique value

In MySQL database, I have a products table containing various product data, including company.
id
name
company
1
Product 1
AAA
2
Another product
BBB
3
One more product
CCC
4
Item ZZZ
BBB
5
Product A
AAA
6
Product uT
DDD
7
Product 2z
AAA
Now I want to build a query which will select all products which have a unique company - I mean a company, which appears only once in the whole table. In the above example - row 3 with company CCC and row 6 with company DDD.
How can I achieve this?
You can use count(id) over(partition by company)
select id, name, company from
(select id, name, company , count(id) over(partition by company) cnt
from products) t
where cnt = 1;
Fiddle
You can use GROUP BY ... HAVING clause to find solo companies, then join to them by the company name.
SELECT * FROM products p
JOIN
(SELECT company FROM products
GROUP BY company
HAVING COUNT(*) = 1) pg
ON p.company = pg.company
SQLFiddle here
MySQL will actually let you do this even simpler query. This works in this circumstance because there is only one row in the group you are looking for. If however, you were looking for all the products for companies that have 2 products, the simpler version won't work anymore, as you'll only get one row back. The original query would continue to work with other HAVING clauses like HAVING COUNT(*) > 10
SELECT id, product, company
FROM products
GROUP BY company
HAVING COUNT(*) = 1
You need to group by company and then only select the rows that have one company:
SELECT `id`, `name`, `company` FROM `products` GROUP BY `company` HAVING COUNT(*)=1;

Guidance required for sql query

I have a database with one table as shown below. Here I'm trying to write a query to display the names of medication manufactured by the company that manufactures the most number of medications.
By looking at the table we could say the medication names which belongs to the company id 1 and 2 - because those company manufactures the most medication according to this table, but I'm not sure how to write a query for selecting the same i said before.
ID | COMPANY_ID | MEDICATION_NAME
1 1 ASPIRIN
2 1 GLUCERNA
3 2 SIBUTRAMINE
4 1 IBUPROFEN
5 2 VENOFER
6 2 AVONEN
7 4 ACETAMINOPHEN
8 3 ACETAMINO
9 3 GLIPIZIDE
Please share your suggestions. Thanks!
Several ways to do this. Here's one which first uses a subquery to get the maximum count, then another subquery to get the companies with that count, and finally the outer query to return the results:
select *
from yourtable
where companyid in (
select companyid
from yourtable
group by companyid
having count(1) = (
select count(1) cnt
from yourtable
group by companyid
order by 1 desc
limit 1
)
)
SQL Fiddle Demo
This Query might work. I have not tested but the logic is correct
SELECT MEDICATION_NAME
FROM TABLE where
COMPANY_ID=(SELECT
MAX(counted)
FROM ( SELECT COUNT(*) AS counted FROM TABLE ) AS counts);

MySQL query to count the number of entries grouped by name

I am trying to do a simple query that will count the number of reviews for each company in a database table as follows grouped by name
e.g reviews table
id company_id review
1 1 Great
2 1 Ok
3 1 Bad
4 2 Nice
So this would return company id 1 with 3, and company id 2 with 1. Any ideas on the easiest solution
select company_id, count(company_id) from tablename group by company_id
try
SELECT company_id,Count(1) FROM reviews GROUP BY company_Id;

SQL: Get records that satisfy conditions coming from multiple records

Let's take a simple table that links customer IDs to product IDs if the customer bought a certain product. I'm looking for an SQL (MySQL) that lists all customers who bought specific products.
CustomerID ProductID
1 A // customer 1 bought product A
2 A
1 B
3 A
2 C
3 B
I would like to get a list of customers who bought both A and B (customers 1 and 3) and customers who bought A but not B (customer 2). I need to do this for more than 2 products, about up to 10, like "A and C and D but not B and E and F".
For question: get a list of customers who bought both A and B
SELECT CustomerID
FROM CustomerList
WHERE ProductID IN ('A', 'B')
GROUP BY CustomerID
HAVING COUNT(*) = 2
if uniqueness was not enforce on ProductID for every CustomerID, DISTINCT keyword is required,
SELECT CustomerID
FROM CustomerList
WHERE ProductID IN ('A', 'B')
GROUP BY CustomerID
HAVING COUNT(DISTINCT ProductID ) = 2
SQLFiddle Demo (both queries)
For the second question, "..A and C and D but not B and E and F"
SELECT CustomerID
FROM CustomerList
WHERE ProductID IN ('A', 'C', 'D')
GROUP BY CustomerID
HAVING COUNT(*) = 3 AND
CustomerID NOT IN
(
SELECT CustomerID
FROM CustomerList
WHERE ProductID IN ('B','E','F')
)
SQLFiddle Demo
TRy this::
Select DISTINCT CUSTOMERID from table1 where PRODUCTID='A'
Here's a slightly different approach for this one(test1 is your example table) :
Select customerId, group_concat(ProductId)
, case when (group_concat(ProductId) like '%A%' and group_concat(ProductId) like '%B%') then 'Bought A&B'
when (group_concat(ProductId) like '%A%' and group_concat(ProductId) not like '%B%') then 'Bought A only' end as Flag
from test1
group by customerId
JW's answer works perfectly, I'd just like to make a small addition. I used a simplified example in the question, in the original case the filtering happens on several joined tables. Taking that to this simple example it basically means that ProductID can be NULL. The query works, but runs for 2 minutes. It seems the cause is a MySQL query optimization bug. Changing the subquery condition to
WHERE ProductID IS NOT NULL and ProductID IN('B','E','F')
reduced query time to two seconds.

SQL query distinct with additional select

I need to perform a query in MySQL that returns distinct values for product_id but also I need to select and return 'id' field which is in that particular table.
This query will return distinct product_id's without id:
SELECT DISTINCT product_id FROM orders_cart
This query will use distinct on both fields which and I want to use it on product_id and see the id
SELECT DISTINCT id, product_id FROM orders_cart
It would be quite easy to do on pgsql but I have no idea how to do this on mysql.
Your query is not well-defined: Consider this table
id product_id
1 1
2 2
3 1
4 2
What should your query result be? If you mean
id product_id
1 or 3 1
2 or 4 2
you are in the land of non-deterministic queries.
What you could do is
SELECT MIN(id), product_id FROM orders_cart GROUP BY product_id
which would deterministically produce
id product_id
1 1
2 2
Thats my final code:
The most important bits for this issue were line 1,2 and 4 :)
GROUP BY did the trick :)
SELECT orders_cart.id, product_id, order_id
FROM orders_cart
LEFT JOIN orders_order ON orders_cart.order_id=orders_order.id
WHERE orders_order.status='Wysłano'
GROUP BY orders_cart.product_id