简体   繁体   中英

SQL MIN Function with where clause

This is my Project Table

 Project Table
JNo Name    City
J1  Proj1   London
J2  Proj2   Paris
J3  Proj3   Athens
J4  Proj4   India

And this is my shipment table

Shipment
SNo PNo JNo Qty
S1  P1  J1  50
S1  P1  J2  90
S1  P2  J1  40
S1  P3  J3  20
S2  P1  J3  110
S2  P2  J2  30
S2  P4  J3  10
S2  P3  J1  100
S3  P1  J3  80
S3  P4  J2  70
S3  P4  J2  70
S4  P1  J3  20
S4  P2  J1  60

I want to name of the project having minimum quantity supplied.

I tried. But its return only minimum qty value this is my code

select min(qty) from shipment where jno IN(select jno from project)
SELECT p.name 
FROM Project p, Shipment s
WHERE s.JNo = p.JNo
  AND s.Qty in (SELECT MIN(qty) FROM shipment)

Without using MIN:


    SELECT p.Name, s.Qty
    FROM `project` p
    INNER JOIN `shipment` s ON `p`.`jno` = `s`.`jno`
    ORDER BY `s`.`qty` ASC
    LIMIT 1

This should work as you say

select p.Name, s.Qty 
from Project p, Shipment s
where p.Jno=s.Jno
and s.Qty in(select min(s.Qty) from Shipment s);

Would display Project Name from the Project table and minimum Qty from the shipment table.

The query that you should use is

SELECT project.Name, min(qty) FROM Project 
LEFT JOIN Shipment ON project.JNO = Shipment.JNO

I hope that this can help you.

For the project with the single smallest shipment, try:

select p.name
from project p
join shipment s on p.jno=s.jno
order by s.qty
limit 1

For the project with the smallest total quantity shipped, try:

select name from
(select p.name, sum(s.qty) total_shipped
 from project p
 join shipment s on p.jno=s.jno
 group by p.name
 order by 2) sq
limit 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM