我有这样的表格。
PollingDivision
pdID pdName
1 Homagama
2 Maharagama
3 Kesbewa
PollingBooth
PBID PBName pdivID
1 HP 1
2 HD 2
PollingBoothElection
pbID elecID numofEO
1 1 3
PollingBoothElectionOfficial
pbID elecid eOfficialID
1 1 1
我试图从投票站汇集展位名称,其中分配的选举官方计数(特定elecID的eOfficialID列和PollingBoothElectionOfficial表中的pbID的数量)小于PollingBoothElection中的选举官方数量表格由投票处。
这是我尝试过的。
SELECT
PB.PBName, COUNT(PBEO.eOfficialID) AS EOCount
FROM
PollingBoothElection PBE
INNER JOIN
PollingBooth PB ON PBE.pbID = PB.PBID
INNER JOIN
PollingDivision PD ON PB.pdivID = PD.pdID
INNER JOIN
PollingBoothElectionOfficial PBEO ON PBE.elecID = PBEO.elecID
AND PBE.pbID = PBEO.pboothID
WHERE
PBE.elecID = 1
AND PD.pdName = 'Homagama'
GROUP BY
PB.PBName, PBE.numOfEO
HAVING
COUNT(PBEO.eOfficialID) < (PBE.numOfEO);
虽然我的表中有数据但它没有给我一个结果。我在这里做错了什么?
预期结果
pbName Count
HP 1
因为对于投票站,HP的eo数为3,但在PollingBoothElectionOfficial表中,pbid1 elecid 1只有1条记录,因此计数小于eos的数量(numOfEO)。
答案 0 :(得分:0)
我会把它放在这里,因为我会超出评论限制。
您的查询会产生您期望的结果:
示例数据
CREATE TABLE PollingDivision(
pdID INT,
pdName VARCHAR(20)
)
CREATE TABLE PollingBooth(
PBID INT,
PBName VARCHAR(20),
pdivID INT
)
CREATE TABLE PollingBoothElection(
pbID INT,
elecID INT,
numofEO INT
)
CREATE TABLE PollingBoothElectionOfficial(
pbID INT,
electID INT,
eOfficialID INT
)
INSERT INTO PollingDivision VALUES (1, 'Homagama'), (2, 'Maharagama'), (3, 'Kesbewa');
INSERT INTO PollingBooth VALUES (1, 'HP', 1), (2, 'HD', 2);
INSERT INTO PollingBoothElection VALUES (1, 1, 3);
INSERT INTO PollingBoothElectionOfficial VALUES (1, 1, 1);
您的(已格式化)查询:
SELECT
PB.PBName,
COUNT(PBEO.eOfficialID) AS EOCount
FROM PollingBoothElection PBE
INNER JOIN PollingBooth PB
ON PBE.pbID = PB.PBID
INNER JOIN PollingDivision PD
ON PB.pdivID = PD.pdID
INNER JOIN PollingBoothElectionOfficial PBEO
ON PBE.elecID = PBEO.electID --replaced PBEO.elecID with PBEO.electID
AND PBE.pbID = PBEO.pbID -- replaced PBEO.pboothID with PBEO.pbID
WHERE
PBE.elecID = 1
AND PD.pdName = 'Homagama'
GROUP BY PB.PBName, PBE.numOfEO
HAVING COUNT(PBEO.eOfficialID) < (PBE.numOfEO);
<强> RESULT 强>
PBName EOCount
-------------------- -----------
HP 1
答案 1 :(得分:0)
这应该有助于满足您的需求:
Select PBName, SUM(eOfficialIDCount)[Count]
from (Select pbID, elecID, Count(Distinct eOfficialID)eOfficialIDCount
from PollingBoothElectionOfficial Group by pbID, electID)A
Left Join (Select pbID, elecID, numofEO from PollingBoothElection)B On B.pbID+b.elecID = A.pbID+a.elecID
Left Join (Select pbID, PBName from PollingBooth)C On C.pbID = A.pbID
Where eOfficialIDCount < numofEO Group by PBName