SQL - 使用ID查找AVG,MIN,MAX和SUM

时间:2016-06-15 15:21:35

标签: sql ms-access

我得到的任务要求我找出Tiddles猫'P0001'和兽医Trevor McCafferty'VO4'的平均,最低,最高和总成本。这将来自两个表,宠物和访问。

宠物表结构:

pet_id, Name, Type, Breed, Gender, Born, owner_id, Notes

访问表格结构:

visit_id, pet_id, vet_id, Visit_Date, Basic_Cost, Symptom, Treatment

以下是我到目前为止创建的命令,但我不确定我是否正确执行此操作,这就是我需要帮助的原因。

SELECT Name, Type, AVG(Basic_Cost), MIN(Basic_Cost), MAX(Basic_Cost), SUM(Basic_Cost)
FROM visit, pet
WHERE pet_id = 'P0001' AND vet_id = 'V04';

任何问题只是问及任何帮助都会受到赞赏,因为我很难过。

2 个答案:

答案 0 :(得分:1)

SELECT FIRST(pet.Name) AS PetName,
    FIRST(pet.Type) AS PetType,
    AVG(Basic_Cost) AS AverageCost,
    MIN(Basic_Cost) AS MinCost,
    MAX(Basic_Cost) AS maxCost,
    SUM(Basic_Cost) AS TotalCost
FROM visit
    INNER JOIN pet ON visit.pet_id = pet.pet_id 
WHERE visit.pet_id = 'P0001'
    AND visit.vet_id = 'V04'

答案 1 :(得分:0)

我认为你遗失了GROUP BY

SELECT pet.Name, pet.Type, AVG(Basic_Cost), MIN(Basic_Cost), MAX(Basic_Cost), SUM(Basic_Cost)
FROM visit, pet 
where visit.pet_id = pet.pet_id 
 and visit.pet_id = 'P0001' 
 and visit.vet_id = 'V04'
GROUP BY pet.Name, pet.Type;

你也可能要加入参观和宠物桌