我有3個表:SQL查詢與聯接和GROUP BY
我想ConsultantBalance,金額和TAXAMOUNT GROUP BY ConsultantId的總和。預期結果:
我想不會太複雜的SQL查詢,避免子查詢,如果可能的。
SQL查詢來創建結構:
CREATE TABLE IF NOT EXISTS `ConsultantBalance` (`id` int(11) NOT NULL AUTO_INCREMENT, `ConsultantID` int(11) DEFAULT NULL, `BalanceType` int(11) DEFAULT NULL, `ConsultantBalance` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=6 ;
INSERT INTO `ConsultantBalance` (`id`, `ConsultantID`, `BalanceType`, `ConsultantBalance`) VALUES (1, 1, 1, 100.00), (2, 1, 2, 50.00), (3, 2, 1, 200.00), (4, 2, 2, 230.00), (5, 3, 1, 300.00);
CREATE TABLE IF NOT EXISTS `ConsultantCredit` (`id` int(11) NOT NULL AUTO_INCREMENT, `ConsultantID` int(11) DEFAULT NULL, `CreditType` char(10) DEFAULT NULL, `Amount` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=7 ;
INSERT INTO `consultantCredit` (`id`, `ConsultantID`, `CreditType`, `Amount`) VALUES (1, 1, 'Deposit', 23.00), (2, 1, 'Cash', 942.00), (3, 2, 'Deposit', 17.00), (4, 2, 'Cash', 932.00), (5, 3, 'Deposit', 125.00), (6, 3, 'Cash', 922.00);
CREATE TABLE IF NOT EXISTS `ConsultantTax` (`id` int(11) NOT NULL AUTO_INCREMENT, `ConsultantID` int(11) DEFAULT NULL, `TaxName` char(5) DEFAULT NULL, `TaxAmount` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=7 ;
INSERT INTO `ConsultantTax` (`id`, `ConsultantID`, `TaxName`, `TaxAmount`) VALUES (1, 1, 'GST', 7.00), (2, 1, 'HST', 10.00), (3, 2, 'GST', 17.00), (4, 2, 'HST', 150.00), (5, 3, 'GST', 37.00), (6, 3, 'HST', 140.00);