I have a little question: I have a view and want to make a small recursive (my approach) call to a table called employee. There are the employees and a column "reportsTo", which gives the EmployeeId of the respective superior or parent.
There is also an invoice table with all purchases made by customers. The customers have a direct contact person / seller (SupportRepId). Now the annual sales of the employees are to be listed, as well as those of the direct employees. (Reverse ReportTo!)
create view employee_sales_v as
select employee.LastName, employee.ReportsTo, sum(invoice.total) sales,
year(invoice.InvoiceDate) year
from employee
join customer on customer.SupportRepId = employee.EmployeeId
join invoice on invoice.CustomerId = customer.CustomerId
group by employee.LastName, year(invoice.InvoiceDate);
How can I get these sales?
SampleData:
CREATE TABLE `Customer`
(
`CustomerId` INT NOT NULL AUTO_INCREMENT,
`SupportRepId` INT,
CONSTRAINT `PK_Customer` PRIMARY KEY (`CustomerId`)
);
CREATE TABLE `Employee`
(
`EmployeeId` INT NOT NULL AUTO_INCREMENT,
`LastName` NVARCHAR(20) NOT NULL,
`FirstName` NVARCHAR(20) NOT NULL,
`ReportsTo` INT,
CONSTRAINT `PK_Employee` PRIMARY KEY (`EmployeeId`)
);
CREATE TABLE `Invoice`
(
`InvoiceId` INT NOT NULL AUTO_INCREMENT,
`CustomerId` INT NOT NULL,
`InvoiceDate` DATETIME NOT NULL,
`Total` NUMERIC(10,2) NOT NULL,
CONSTRAINT `PK_Invoice` PRIMARY KEY (`InvoiceId`)
);
INSERT INTO `Employee` (`LastName`, `FirstName`, `ReportsTo`) VALUES (N'HGF', N'POI', 0);
INSERT INTO `Employee` (`LastName`, `FirstName`, `ReportsTo`) VALUES (N'XYZ', N'ABC', 1);
INSERT INTO `Customer` (`SupportRepId`) VALUES (2);
INSERT INTO `Customer` (`SupportRepId`) VALUES (2);
INSERT INTO `Invoice` (`CustomerId`, `InvoiceDate`, `Total`) VALUES (1, '2013/1/1', 1.98);
INSERT INTO `Invoice` (`CustomerId`, `InvoiceDate`, `Total`) VALUES (2, '2009/10/2', 3.96);
INSERT INTO `Invoice` (`CustomerId`, `InvoiceDate`, `Total`) VALUES (2, '2010/5/3', 5.94);