MySQL: Select rows where field contains unique value - mysql

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;

Related

select records as a single with different queries

I have a table, the table structure of which is as follows
id service_type pincode
---------------------------------
1 B 695582
2 D 676102
3 P 685584
4 B 685608
I will get two different pincodes from the front end. say for example 695582 and 685608. I need to get the service_types at these pincodes with single query and the results should be a single row. I have tried a UNION query, but the results are in two different row.
select 'buyer' name, service_type from tm_location_carrier_lnk where pincode=695582
UNION
select 'seller' name, service_type from tm_location_carrier_lnk where pincode=685608
The result of the above query is as follows
name service_type
------------------
buyer B
seller B
How can i get results in a single row as follows
Buyer Seller
B B
Why not doing
SELECT (select service_type from tm_location_carrier_lnk where pincode=695582 LIMIT 1) as Buyer, (select service_type from tm_location_carrier_lnk where pincode=685608 LIMIT 1) as Seller;
Here you can find a working example: http://sqlfiddle.com/#!9/e01426/1
edit: added LIMIT 1 for avoiding duplicated pincodes.
One solution assuming unique pincodes and specific to your request:
Select
(select max(service_type)
from tm_location_carrier_lnk
where pincode=695582) as Buyer
, (select max(service_type)
from tm_location_carrier_lnk
where pincode=685608) as Seller;

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);

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

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';

MYSQL: Finding out last record from multiple records each having same value for a particular column

Could any one please help me with MySql database query:
I have one table with below data:
work_date ticket no category
------------------------------------
7/15/2013 111 a
7/15/2013 222 b
7/15/2013 333 c
7/16/2013 111 a
7/16/2013 555 e
7/16/2013 333 f
7/17/2013 111 H
I need help in writing a query which will read all table data, then create 2 columns one ticket no and second as category. Under ticket column it would show count of all distinct ticket number and value under category should be the last category assigned to that ticket.
i'm using the following query
SELECT category, count(distinct(ticket_no))
FROM master
group by category
order by 2 DESC`
the ticket which is present in 2 or more categories are being counted multiple times, I want it to be counted just once and that too the latest one
Expected Result:
Ticket No Category
--------------------
111 H
222 b
333 f
555 e
I don't get your sample query. It is grouping by category and not ticket, but the sample data is by ticket.
In any case, I think this does what you want:
select ticket,
substring_index(group_concat(category order by work_date desc), ',', 1)
from master m
group by ticket;
select * from
(select ticket_no,category from master order by work_date desc) abc
group by ticket_no;
fiddle
You can use the following SQL Query:
SELECT DISTINCT(ticket_no), category FROM table_name SORT BY DESC;
SELECT *
FROM distinct t1
WHERE NOT EXISTS (
SELECT *
FROM distinct t2
WHERE t2.ticket_no= t1.ticket_no
AND t2.work_date > t1.work_date
);
here work_date should be a formatted timestamp

Select grouped by two columns with Count

Im having problems trying to understand how to build this query.
My data scheme:
id category name userid
1 sports football 1
2 cars ferrari 1
3 sports basketball 1
4 film Matrix 9
5 film Fauno 9
6 sports Surf 3
As you can see the category can be repeated even for a same user id because the name field is different. So my idea is to get the categories of a set of users and the amount of users for each categories on that set.
Lets say i have the set of user set_of_user = (1,9,3), If i run the query
SELECT something FROM category_table WHERE userid IN set_of_user SOME CONDITION HERE
The correct result should be:
category: sports
users: 2
category: cars
users: 1
category: film
users: 1
My best shot was:
SELECT userid, category, COUNT(userid) as users from interests WHERE `userid` in ' . $norm_info_ids . ' GROUP BY category
But this gave a bad result, how can i solve this?
I think this is what you're looking for using COUNT with DISTINCT, along with GROUP BY:
select category, count(distinct userid)
from interests
where userid in (1,3,9)
group by category
SQL Fiddle Demo
Resulting in:
CATEGORY COUNT(DISTINCT USERID)
cars 1
film 1
sports 2
First you need to select the distinct paring of category and user id
select t.category, count(t.user_id)
from
(
SELECT distinct category,user_id
from tab
where user_id in (1,3,9)
) t
group by t.category