联接3张桌子以获得总目标和总销售额

时间:2019-07-10 08:23:29

标签: sql sql-server join

我的数据库中有3个表,如下所示:

Sman表

smanID  |  smanName  | smanTeam    
-------------------------------
0210    | John       | Direct
0211    | Stacy      | Indirect
0212    | Bob        | Indirect

SalesTarget表

Period    | smanID    |  Target
-------------------------------
201901    | 0210      | 200000
201902    | 0210      | 200000
201901    | 0211      | 200000
201902    | 0211      | 200000
201901    | 0212      | 200000
201902    | 0212      | 200000

销售表

Period    | smanID    |  SalesID  | Amount
------------------------------------------
201901    | 0210      |  abc121   | 20000
201901    | 0210      |  abc122   | 80000
201901    | 0211      |  abc123   | 150000
201901    | 0212      |  abc124   | 30000
201902    | 0210      |  abc125   | 35000
201902    | 0211      |  abc126   | 80000
201902    | 0212      |  abc127   | 22000

我想获得每个销售团队产生的总目标,总销售额和超额销售百分比。

我正在运行SQL Server 2012。

这是我尝试过的方法,但除TotalSales列外,我没有获得正确的结果:

SELECT C.smanTeam,
       COALESCE(SUM(A.Target), 0) AS TotalTarget,
       COALESCE(ROUND((SUM(B.[Amount)), 2), 0) AS TotalSales,
       COALESCE(ROUND((((SUM(B.[Amount])) / COALESCE(SUM(A.SalesTarget), '0')) * 100), 0), 0) AS TotalPercentage
FROM Sman_SalesTarget_Current A
     LEFT JOIN [SALESORDER] B ON B.smanID = A.smanID
                             AND B.Period = A.Period
     LEFT JOIN Sman C ON B.smanID = C.SmanID
WHERE B.Period BETWEEN '201901' AND '201902'
GROUP BY C.smanTeam
ORDER BY C.smanTeam;

我想要的结果应该是这样的:

salesTeam  | TotalTarget  | TotalSales  | TotalPercentage
---------------------------------------------------------
Direct     | 400000       | 135000      |     33
Indirect   | 800000       | 282000      |     35

任何人都可能指出我的查询在哪里出错了?我在想加入语句,但仍然无法解决。

2 个答案:

答案 0 :(得分:1)

尝试一下-

SELECT A.smanTeam,
A.TotalTarget,
B.TotalSales,
B.TotalSales*100/A.TotalTarget TotalPercentage
FROM
(
    SELECT smanTeam,SUM(Target) TotalTarget
    FROM Sman S
    INNER JOIN SalesTarget ST ON S.smanID  = ST.smanID
    GROUP BY smanTeam
)A
LEFT JOIN
(
    SELECT smanTeam, SUM(Amount) TotalSales
    FROM Sman S
    INNER JOIN Sales SA ON S.smanID  = SA.smanID
    GROUP BY smanTeam
)B ON A.smanTeam = B.smanTeam

答案 1 :(得分:0)

请尝试以下查询:

select smanTeam, sum(Target) TotalTarget, sum(Amount) TotalSales , sum(Target)/sum(Amount) TotalPercentage from (
    select smanTeam, Target, Amount from Sman sm
    join
        (select smanID, sum(Target) Target from SalesTarget group by smanID) st
        on sm.smanID = st.smanID
    join
        (select smanID, sum(Amount) Amount from Sales group by smanID) s
        on sm.smanID = s.smanID
) a group by smanTeam