0

考虑以下 MySQL 表:


死亡率(包含哪些饲养者死亡的仔猪)

raiserID  |  issuedDate  |  rotationNo |  numberDead
-----------------------------------------------------
   0052      2012-08-03         1             3


PIGLET_PO(包含饲养者购买仔猪交易)

~ raisers 可以在这里有多个记录

raiserID  |  deliveredDate  |  rotationNo  |  noOfDeliveredPigs  |  sellerID
------------------------------------------------------------------------------
   0052       2012-07-20          1                  10                1
   0052       2012-07-21          1                  15                1


SELLER_LIST

sellerID |  sellerName  
------------------------
    1       Solar Farm


预期结果:

sellerName  |  population  |  deceased
-----------------------------------------
Solar Farm         25            3     


  • 饲养员是照顾/饲养猪/猪的人
  • rotationNo 是一个唯一标识符,表示饲养者已经进行或当前正在进行的饲养周期

到目前为止,我有以下查询,它给我的结果类似于预期的结果,唯一的问题是我得到的值为 6 而不是 3 的已故列。我不确定,但我的猜测是它与 piglet_po 有两个记录/行有关。我在这里想念什么?

SELECT s.sellerName AS sellerName, SUM(p.noOfDeliveredPigs) AS population, SUM(numberDead) AS heads
FROM mortality m

JOIN piglet_po p
ON m.raiserid = p.raiserid
AND m.rotationNo = p.rotationNo

JOIN seller_list s
ON p.sellerID = s.sellerID

// This WHERE condition and the given string value that follow came from and is based on
a select drop-down box and shouldnt be modified since this is how I display them in html WHERE DATE_FORMAT(m.issuedDate, '%M %Y') = 'August 2012' GROUP BY sellerName HAVING SUM(numberDead) != 0
4

2 回答 2

1

这是因为您在 join for table 中使用的列的值重复piglet_po(p.rotationNo)。相反,试试这个,或者你也可以DISTINCT在语句中使用子句SELECT

SELECT s.sellerName AS sellerName, SUM(p.noOfDeliveredPigs) AS population, 
       SUM(numberDead) AS heads
FROM mortality m
    JOIN (SELECT rotationNo, raiserid, sellerID, SUM(noOfDeliveredPigs) AS noOfDeliveredPigs
          FROM  piglet_po 
          GROUP BY rotationNo, raiserid, sellerID
         ) p
         ON m.raiserid = p.raiserid
            AND m.rotationNo = p.rotationNo
    JOIN seller_list s
         ON p.sellerID = s.sellerID
WHERE DATE_FORMAT(m.issuedDate, '%M %Y') = 'August 2012'
GROUP BY sellerName
HAVING SUM(numberDead) != 0;
于 2012-08-09T11:58:20.043 回答
1

试试这个:

select sellername , population  , deceased 
from
    (select p.rotationno,p.raiserid,s.sellername as sellername
           , sum(p.noofdeliveredpigs) as population 
    from piglet_po p
    join seller_list s
    on p.sellerid = s.sellerid 
    group by p.rotationno,p.raiserid,sellername)p
join
    (select rotationno,raiserid,sum(numberdead) as deceased
    from mortality 
    where date_format(issueddate, '%m %y') = 'august 2012'
    group by rotationno,raiserid)m
on m.raiserid = p.raiserid
and m.rotationno = p.rotationno
于 2012-08-09T12:55:34.120 回答