SQL GROUP BY函数返回不正确的SUM量

时间:2018-04-26 09:12:08

标签: sql sql-server group-by sum

我一直在研究这个问题,研究我可能做错的事情,但我似乎无法在我编写的代码中找到答案或错误。我目前正从MS SQL Server数据库中提取数据,WHERE子句成功地将结果过滤到我想要的结果。我每个员工大约有4行,并希望将值列添加到一起。当我针对员工ID添加GROUP BY子句并对值进行SUM时,我得到一个完全错误的数字。我怀疑SQL代码忽略了我的WHERE子句。

以下是一小部分数据:

hr_empl_code    hr_doll_paid
1               20.5
1               51.25
1               102.49
1               560

我希望GROUP BY和SUM子句给我734.24的值。给出的值是211461.12。通过问题排查,我在查询中添加了一个COUNT(*)列,以确定它运行了多少行,并且它给出了1152的结果,进一步强化了我对它的信念。忽略我的WHERE子句。

我的SQL代码如下。其中大部分是由我运行它的前端应用程序生成的,因此我认为其中有一些额外的代码可以帮助查询。

SELECT DISTINCT
    T000.hr_empl_code,
    SUM(T175.hr_doll_paid)
FROM 
    hrtempnm T000,
    qmvempms T001,
    hrtmspay T166,
    hrtpaytp T175,
    hrtptype T177
WHERE   1 = 1 
AND T000.hr_empl_code = T001.hr_empl_code
AND T001.hr_empl_code = T166.hr_empl_code
AND T001.hr_empl_code = T175.hr_empl_code
AND T001.hr_ploy_ment = T166.hr_ploy_ment
AND T001.hr_ploy_ment = T175.hr_ploy_ment
AND T175.hr_paym_code = T177.hr_paym_code
AND T166.hr_pyrl_code = 'f' AND T166.hr_paid_dati = 20180404
AND (T175.hr_paym_type = 'd' OR T175.hr_paym_type = 't')
GROUP BY T000.hr_empl_code
ORDER BY hr_empl_code

我真的迷失了可能出错的地方。我已经删除了额外的WHERE AND并将其降低到T166.hr_empl_code = T175.hr_empl_code,但它并没有做出与众不同的事。

我绝不是SQL Server和查询的专家,但我对这项技术有很好的把握。任何帮助将非常感谢!

1 个答案:

答案 0 :(得分:1)

分组没有错,你如何使用它是错误的。

SELECT 
    T000.hr_empl_code,
    T.totpaid
FROM 
    hrtempnm T000
inner join (SELECT 
    hr_empl_code,
    SUM(hr_doll_paid) as totPaid
FROM 
    hrtpaytp T175
where hr_paym_type = 'd' OR hr_paym_type = 't'
GROUP BY hr_empl_code
) T on t.hr_empl_code = T000.hr_empl_code
where exists
   (select * from qmvempms T001,
    hrtmspay T166,
    hrtpaytp T175,
    hrtptype T177
WHERE  T000.hr_empl_code = T001.hr_empl_code
AND T001.hr_empl_code = T166.hr_empl_code
AND T001.hr_empl_code = T175.hr_empl_code
AND T001.hr_ploy_ment = T166.hr_ploy_ment
AND T001.hr_ploy_ment = T175.hr_ploy_ment
AND T175.hr_paym_code = T177.hr_paym_code
AND T166.hr_pyrl_code = 'f' AND T166.hr_paid_dati = 20180404
)
ORDER BY hr_empl_code

注意:如果您使用了连接而不是旧式连接到哪里,那就更清楚了。