Grouping and looping in a stored procedure

前端 未结 1 601
梦如初夏
梦如初夏 2021-01-27 21:38

I need to do a sum on the columns MTH1 MTH2 etc but for the parameters I pass it will produce six rows of information for the same account code which is correct and what it shou

相关标签:
1条回答
  • 2021-01-27 22:19

    You seem to simply want a GROUP BY. But you can also simplify the query in other ways:

    select nl.ACCOUNT_REF, 
        sum(nl.PRIOR_YR_MTH1) as PRIOR_YR_MTH1,
        sum(nl.PRIOR_YR_MTH2) as PRIOR_YR_MTH2,
        . . .  - fill in the rest of the months
    from NOMINAL_LEDGER nl join         
         CATEGORY c
         on c.CompanyID = nl.CompanyID
    where nl.ACCOUNT_REF = @AccountRef and
          nl.SORT_ORDER = @SortOrder and
          c.CATEGORY = @CATEGORY
    group by nl.ACCOUNT_REF;
    

    Notes:

    • The WHERE clause (presumably) undoes the LEFT JOIN, turning it into an INNER JOIN. So use the proper JOIN.
    • Table aliases make the query easer to write and to read.
    • You seem to want one row per account, so the query aggregates by account and leaves out the other non-aggregated columns.
    0 讨论(0)
提交回复
热议问题