我有两个表:
Receive_Amount_Details
用于从施工现场所有者处贷记金额,并且SitewiseEmployee
是借方借方支付给劳工的款项。对于两个表中都存在的每个Date
,我想:
Amount_Received
中的所有Receive_Amount_Details
总计为Total_Receive_Amount_from_siteowner
,并且Amount
中的所有SitewiseEmployee
都作为Total_Amount_Payed_to_Labour
输出表上的列。两个表都具有Date
列,但我希望输出中有一个Date
列。
如果未收到任何单日金额并支付了人工,则应将其显示在输出表中,并且如果收到任何单日金额但未支付劳力的工资,则也应将其显示在输出表中
CREATE TABLE `Receive_Amount_Details` (
`Id` int(10) NOT NULL AUTO_INCREMENT,
`SiteId` int(5) NOT NULL,
`Amount_Received` int(10) NOT NULL,
`Date` date NOT NULL,
PRIMARY KEY (`Id`),
KEY `SiteId` (`SiteId`),
CONSTRAINT `Receive_Amount_Details_ibfk_1` FOREIGN KEY (`SiteId`)
REFERENCES `SiteList` (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
和
CREATE TABLE `SitewiseEmployee` (
`Id` int(10) NOT NULL AUTO_INCREMENT,
`SiteId` int(5) NOT NULL,
`EmployeeId` int(10) NOT NULL,
`Amount` varchar(10) DEFAULT NULL,
`Date` date NOT NULL,
PRIMARY KEY (`Id`),
KEY `SiteId` (`SiteId`),
KEY `EmployeeId` (`EmployeeId`),
CONSTRAINT `SitewiseEmployee_ibfk_1` FOREIGN KEY (`SiteId`)
REFERENCES `SiteList` (`Id`),
CONSTRAINT `SitewiseEmployee_ibfk_2` FOREIGN KEY (`EmployeeId`)
REFERENCES `Employee` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
答案 0 :(得分:0)
假设一个表中的日期可能不存在于另一个表中,反之亦然,那么您将需要执行完全外部联接。 MySql没有这种联接类型,但是可以通过并集来实现它:
select `Date`,
sum(Amount_Received) as Sum_Amount_Received,
sum(Amount) as Sum_Amount
from (
select `Date`, Amount_Received, 0 as Amount
from Receive_Amount_Details
union
select `Date`, 0, Amount
from SitewiseEmployee
) as dates
group by `Date`;