Dear Experts,
I am having a Sales Data with assigned Sales Targets. Final Targets are to be calculated as per reporting matrix.
A=>Highest Level
B=>Middle Level
C=>Lowest Level
that means C is reporting to B and B inturn is reporting to A.
Target of A = Target of A + Target of B + Target of C
Target of B = Target of B + Target of C
Target of C = Target Assigned.
The sample table containing the data is as follows:-
+--------+--------+-------------------+
| SPName | Target | ReportingHeadName |
+--------+--------+-------------------+
| A | 200 | A |
| B1 | 100 | A |
| B2 | 300 | A |
| C1 | 50 | B1 |
| C2 | 75 | B1 |
| C3 | 60 | B2 |
+--------+--------+-------------------+
Following is query to create sample table i.e. mytable4
CREATE TABLE mytable4(
SPName VARCHAR(2) NOT NULL PRIMARY KEY
,Target INTEGER NOT NULL
,ReportingHeadName VARCHAR(2) NOT NULL
);
INSERT INTO mytable4(SPName,Target,ReportingHeadName) VALUES ('A',200,'A');
INSERT INTO mytable4(SPName,Target,ReportingHeadName) VALUES ('B1',100,'A');
INSERT INTO mytable4(SPName,Target,ReportingHeadName) VALUES ('B2',300,'A');
INSERT INTO mytable4(SPName,Target,ReportingHeadName) VALUES ('C1',50,'B1');
INSERT INTO mytable4(SPName,Target,ReportingHeadName) VALUES ('C2',75,'B1');
INSERT INTO mytable4(SPName,Target,ReportingHeadName) VALUES ('C3',60,'B2');
the desired output is as follows:-
+--------+-------------+
| SPName | FinalTarget |
+--------+-------------+
| A | 785 |
| B1 | 225 |
| B2 | 360 |
| C1 | 50 |
| C2 | 75 |
| C3 | 60 |
+--------+-------------+
As per the suggestion given to me by an helpful expert the following query was designed
With CTE
As
(
Select
T1.SPName
,MAX(T1.Target) as T1
,SUM(T2.Target) as T2
,sum(T3.Target) as T3
From
mytable4 as T1
Left Outer Join mytable4 as T2 on T1.SPName = T2.ReportingHeadName AND T1.SPName <> T2.SPName
Left Outer Join mytable4 as T3 on T2.SPName = T3.ReportingHeadName
GrouP by
T1.SPName
)
Select
C.SPName,C.T1+ISNULL(C.T2,0)+ISNULL(C.T3,0) as FinalTarget
From
CTE as C
But the output I am getting is as follows:-
+--------+-------------+
| SPName | FinalTarget |
+--------+-------------+
| A | 885 |
| B1 | 225 |
| B2 | 360 |
| C1 | 50 |
| C2 | 75 |
| C3 | 60 |
+--------+-------------+
The only problem in the above output is Final Target Value of A which is 885 but actually it should have been 785. The target column cannot be totalled as it is for position A as there may multiple employees at Top Level i.e. A1, A2 A3 whose reporting matrix would be different from A (as above).
Can somebody help me to achieve the desired output by giving your valuable suggestion/advice?
Thanks in advance for your help.