programmer001
programmer001

Reputation: 69

Showing maximum

I want to show maximum of guarantee which specific user has. For example user has bought 3 items which have 1,2,5 years guarantee. So I want to show 5 years guarantee and name of this product. I did subquery in case few products have this same guarantee.

SELECT t.`id-user`, name, guarantee FROM transactions t 
JOIN user u ON `t`.`id-user` = `u`.`id-user`
JOIN products p ON `p`.`id-product = `t`.`id-product`
WHERE guarantee = (SELECT MAX(p2.guarantee) 
                   FROM products p2
                   WHERE `p2`.`id-product` = `p`.`id-product`)

This query shows all products and their guarantees.

Upvotes: 0

Views: 38

Answers (2)

Mehrdad
Mehrdad

Reputation: 1

I think it work.

select [User].Name as [UserName],
     Product.MaxGuarantee,
     Product.Name as Product_Name
from [Users] [User]
     left join Transactions [Transaction]
          on [Transaction].[User] = [User].ID
     cross apply(
          select max(guarantee) MaxGuarantee, Name
     from Products
     where ID = [Transaction].Product
     ) Product
where [User].ID = ''

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1270513

I think the simplest method is the substring_index()/group_concat() method for getting values associated with a maximum/minimum:

SELECT t.iduser, u.name,
       MAX(p.guarantee) as guarantee,
       SUBSTRING_INDEX(GROUP_CONCAT(p.name ORDER BY p.guarantee DESC), ',', 1)
FROM transactions t JOIN 
     user u 
     ON t.iduser = u.iduser JOIN
     products p
     ON p.idproduct = t.idproduct
GROUP BY t.iduser, u.name;

You can use your method too, but the correlated subquery is tricky:

SELECT t.iduser, u.name, p.guarantee, p.name
FROM transactions t JOIN 
     user u 
     ON t.iduser = u.iduser JOIN
     products p
     ON p.idproduct = t.idproduct
WHERE p.guarantee = (SELECT MAX(p2.guarantee)
                     FROM transactions t2 JOIN
                          products p2
                          ON p2.idproduct = t2.idproduct
                     WHERE t2.iduser = u.iduser
                    );

Upvotes: 1

Related Questions