TSQL:SUM不像我想的那样工作

时间:2016-01-07 15:54:58

标签: sql-server tsql

我有以下查询:

SELECT 
    a.Name,
    ISNULL(CAST(sum((b.qty * b.unit_rate)* b.Eng_RPQ )/100 AS DECIMAL(8,1)),0) AS [EngHours],
    SUM(BR.BlendedRate)
FROM 
    Activity_Details b
INNER JOIN 
    Activity c on b.activity_id = c.id
INNER JOIN 
    Project p on p.id = c.project_id
RIGHT OUTER JOIN 
    Discipline a on c.discipline_id = a.id
INNER JOIN 
    (SELECT 
         a.Name, c.id, 
         CAST(f.POH * (d.HourlyRate * (1-(r.Discount/100))/100) AS DECIMAL(8,2)) AS BlendedRate 
     FROM 
         Activity_Details b
     INNER JOIN 
         Activity c on b.activity_id = c.id
     INNER JOIN 
         Team f on f.activity_id = c.id
     INNER JOIN 
         SOF_Details d on d.id = f.sof_detail_id
     INNER JOIN 
         Project p on p.id = c.project_id
     INNER JOIN 
         Rate r on r.projectid = p.id
     INNER JOIN 
         Teammate_Type tt on tt.id = f.team_type_id
     RIGHT OUTER JOIN 
         Discipline a on c.discipline_id = a.id
     GROUP BY 
         a.Name, c.id, f.POH, d.HourlyRate, r.Discount) AS BR ON BR.id = c.id
GROUP BY 
    a.Name
ORDER BY 
    a.Name

哪个收益率:

Name            EngHours   BlendedRate
Architechtural  80.8       38.48
Architechtural  80.8       55.33
Architechtural  80.8       55.40

我想要将此BlendedRate和ROUND它相加但是如果我尝试SUM(BR.BlendedRate)到SELECT并删除GROUP BY中的BR.BlendedRate

我明白了:

Name            EngHours    BlendedRate
Architechtural  242.3       895.26

我期待BlendedRate等于149.21

知道我做错了吗?

1 个答案:

答案 0 :(得分:-1)

由于声誉无法发表评论。这是一个粗略的解决方案,但您的代码返回重复(看似6)记录。代码应该在别处修复,但没有样本数据很难。同时,原始解决方案是在sum函数中添加一个distinct子句

SUM( DISTINCT BR.BlendedRate)