我无法弄清楚如何在SQL中编写查询。
这是我的表格,
CREATE TABLE offences (
oOffenceID VARCHAR (30),
oDescription VARCHAR (200),
oMaximumFine INT (10),
CONSTRAINT o_pk
PRIMARY KEY (oOffenceID)
);
CREATE TABLE drivers (
dPersonID VARCHAR (30),
dLicenseNumber INT (20),
dLicenseRemoved ENUM('yes','no'),
dExpiryDate DATE,
CONSTRAINT d_pk
PRIMARY KEY (dLicenseNumber),
CONSTRAINT d_fk
FOREIGN KEY (dPersonId)
REFERENCES People (pPersonID)
);
CREATE TABLE people (
pPersonID VARCHAR (30),
pName VARCHAR (30),
pAddress VARCHAR (50),
pNIN VARCHAR (30),
CONSTRAINT p_pk
PRIMARY KEY (pPersonID)
);
CREATE TABLE vehicle (
vOwnerID VARCHAR (30),
vColour VARCHAR (30),
vModel VARCHAR (30),
vMake VARCHAR (30),
vVehicleID VARCHAR (30),
CONSTRAINT v_pk
PRIMARY KEY (vVehicleID),
CONSTRAINT v_fk
FOREIGN KEY (vOwnerID)
REFERENCES People (pPersonID)
);
CREATE TABLE fines (
fFineID INT (30) AUTO_INCREMENT,
fVehicleID VARCHAR (30),
fPersonID VARCHAR (30),
fTime DATE,
fAmount INT (10),
fOfficerStatement VARCHAR (500),
fOffenceID VARCHAR (30),
CONSTRAINT f_pk
PRIMARY KEY (fFineID),
CONSTRAINT f_fk
FOREIGN KEY (fVehicleID)
REFERENCES vehicle (vVehicleID),
CONSTRAINT f_fk1
FOREIGN KEY (fPersonID)
REFERENCES people (pPersonID),
CONSTRAINT f_fk2
FOREIGN KEY (fOffenceID)
REFERENCES offences (oOffenceID)
);
我需要一个查询,显示汽车的VehicleID,所有者的名字以及累计超过1000个罚款的所有汽车累积的罚款总额。有人能看到怎么做吗?
答案 0 :(得分:2)
希望这会让你朝着正确的方向前进:
select fVehicleId,p.pName,sum(fi.totalFines) as totalFinesOver1000ForPerson
from
(select fVehicleId,sum(fAmount) as totalFines
from fines f
group by fVehicleId
having sum(fAmount) > 1000) fi
inner join vehicle v on v.vVehicleID = fi.fVehicleId
inner join people p on v.vOwnerId = p.pPersonId
group by fVehicleId,p.pName;
答案 1 :(得分:0)
Select a.vVehicleID,
b.pName,
sum(d.fAmount) fine
from vehicle a,people b,fines d,drivers e
where a.vVehicleID=d.vVehicleID and d.fPersonID=e.dPersonID and d.fPersonID=a.vOwnerID and
b.pPersonID = e.dPersonID
group by a.vVehicleID,b.pNamem
having fine > 1000;
这应该有效