代码之家  ›  专栏  ›  技术社区  ›  Clauric

SQL搜索中的Sum函数

  •  0
  • Clauric  · 技术社区  · 6 年前

    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
    

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

    Msg 207,级别16,状态1,第5行列名“SDormant”无效。

    编辑:为了更好的解释。

    对于Member\u ID和LoanAccount\u ID,有多个具有相同参数的条目(例如,可能有200个Member\u ID:1,LoanAccount\u ID:200)。其中只有1个可能具有休眠代码(值为1),而其余的可能为空。我需要聚合Member\u id和LoanAccount\u id,并计算休眠字段中有多少个条目有值。希望这是一个更好的解释。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Eric Brandt    6 年前

    GROUP BY 分组依据 SELECT 查询中的子句。在进行分组时, SDormant 还不存在。

    你也不能 一个聚合表达式,因为它使人的头爆炸。

    根据你的编辑,这可能会得到你想要的。它应该显示每个 Member_ID / LoanAccount_ID 一对,总共 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
    
        2
  •  2
  •   Gordon Linoff    6 年前

    我不知道你的问题和你的问题有什么关系。但你通常不会使用 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
    
        3
  •  1
  •   Yogesh Sharma    6 年前

    根据你的描述,我会:

    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 Dormant IS NOT NULL