如何在SQL数据库

时间:2016-09-22 00:43:58

标签: sql ms-access average

使用Sally的宠物商店数据库我试图找出哪些猫花费的时间比普通猫要长。我认为它应该像这样开始......

SELECT AVG (`SaleDate`) AS `Longer to Sale`....

但是当数据库中没有任何内容告诉我时,我对如何获取AVG感到困惑。

这是Access关系表单中的数据库,所以每个人都可以看到

enter image description here

我认为唯一可以使用的表是:AnimalsSaleAnimalAnimalOrderItem

但是一些帮助会很感激,也许是获得它的好解释

1 个答案:

答案 0 :(得分:0)

第1步:卖猫的平均时间是多少?

DECLARE @avg INT;

SELECT @avg = AVG(DATEDIFF(day, ao.ReceiveDate, s.SaleDate))
FROM Animal a
   INNER JOIN SaleAnimal asale ON (a.AnimalID = asale.AnimalID)
   INNER JOIN Sale s ON (asale.SaleID = s.SaleID)
   INNER JOIN AnimalOrderItem aoi ON (a.AnimalID = aoi.AnimalID)
   INNER JOIN AnimalOrder ao ON (aoi.OrderID = ao.OrderID)
WHERE a.Breed = 'cat';

第2步:有多少猫需要更长时间才能卖出去?

SELECT COUNT(1)
FROM Animal a
   INNER JOIN SaleAnimal asale ON (a.AnimalID = asale.AnimalID)
   INNER JOIN Sale s ON (asale.SaleID = s.SaleID)
   INNER JOIN AnimalOrderItem aoi ON (a.AnimalID = aoi.AnimalID)
   INNER JOIN AnimalOrder ao ON (aoi.OrderID = ao.OrderID)
WHERE a.Breed = 'cat'
   AND DATEDIFF(day, ao.ReceiveDate, s.SaleDate) > @avg;