SQL搜索中的求和函数

时间:2018-10-04 16:42:00

标签: sql sql-server

我试图找出系统中在特定字段中有1个帐户的数量。我使用的代码如下:

Select  Member_Id,    
        LoanAccount_ID,
        SUM(Dormant) as SDormant
From    LoanAccountBal
Group by member_ID, LoanAccount_ID, SDormant
Order by Member_ID asc, LoanAccount_ID asc

但是,当我尝试运行此代码时,出现以下错误:

  

消息207,级别16,状态1,第5行,无效的列名称“ Srmant”。

如何获取识别新列名和求和函数的代码?

编辑:解释得更好。

对于Member_ID和LoanAccount_ID,都有多个具有相同参数的条目(例如,可能有200个Member_ID:1,LoanAccount_ID:200)。其中只有1个可能具有休眠代码(值为1),而其余代码可能为空。我需要汇总Member_IDs和LoanAccount_IDs,还要计算Dormant字段中有多少个条目具有值。希望这是一个更好的解释。

3 个答案:

答案 0 :(得分:2)

我不知道您的查询与您的问题有什么关系。但是您通常不会在SUM()的列上使用GROUP BY。所以我认为这是您要编写的查询:

Select Member_Id, LoanAccount_ID, SUM(Dormant) as SDormant
From LoanAccountBal
Group by member_ID, LoanAccount_ID
Order by Member_ID asc, LoanAccount_ID asc;

不过,对于您的问题,我希望您的查询中有一个条件,也许是:

where <some column> = 1

答案 1 :(得分:1)

根据您的描述,我会这样做:

Select Member_Id, LoanAccount_ID, 
       SUM(CASE WHEN <particular field> = 1 THEN 1 ELSE 0 END) as SDormant
From LoanAccountBal
Group by member_ID, LoanAccount_ID
Order by Member_ID asc, LoanAccount_ID asc;

其他选择是将COUNT()WHERE子句一起使用:

Select Member_Id, LoanAccount_ID, COUNT(*) as SDormant
From LoanAccountBal
WHERE <particular field> = 1
Group by member_ID, LoanAccount_ID
Order by Member_ID asc, LoanAccount_ID asc;

编辑:假设空词的意思是null,那么您只需要count()

Select Member_Id, LoanAccount_ID, COUNT(Dormant) as SDormant
From LoanAccountBal
Group by member_ID, LoanAccount_ID
Order by Member_ID asc, LoanAccount_ID asc;

但是,如果您仅将WHERE子句修改为,则第二个版本查询也将起作用:

WHERE Dormant IS NOT NULL

答案 2 :(得分:1)

您遇到的特定错误是因为您无法GROUP BY列别名,因为SQL引擎先评估GROUP BY子句,然后才评估查询中的SELECT子句。在进行分组时,SDormant尚不存在。

您也无法GROUP BY聚合表达式,因为这会使人的头部爆炸。

根据您的编辑,这可能会为您提供所需的东西。它应显示每对Member_ID / LoanAccount_ID,总Dormant贷款,总{em> not Dormant贷款以及这两项的总和,就像进行健全性检查一样。

    Select  Member_Id,    
            LoanAccount_ID,
            SUM(Dormant) AS SDormant,
            SUM(CASE WHEN Dormant = 0 THEN 1 ELSE 0 END) AS NotDormant,
            COUNT(*) AS TotalCount
    From    LoanAccountBal
    Group by member_ID, LoanAccount_ID
    Order by Member_ID asc, LoanAccount_ID asc