考虑以下 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