考虑以下MySQL表:
MORTALITY (包含哪些饲养者已经死亡的仔猪)
raiserID | issuedDate | rotationNo | numberDead
-----------------------------------------------------
0052 2012-08-03 1 3
PIGLET_PO (包含由饲养者购买仔猪交易)
〜提升者可以在此处拥有多条记录
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
到目前为止,我有以下查询给出了类似于预期结果的结果,唯一的问题是我得到的值为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
答案 0 :(得分:1)
这是因为您在表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;
答案 1 :(得分: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