Herman
Herman

Reputation: 157

SQL Server : sum a column

I have tried everything I could to get the Current column added up. 'BF', 'Current' and 'Future' should all equal zero and I just need a quick check to verify it.

The code

SELECT 
    [AccountCode], [ExpensesCode], [CostCentre],
    [NLYear], [NLPeriod],
    SUM([BroughtForward]) AS 'BF',
    SUM([CurrentPostings]) AS 'Current',
    SUM([FuturePostings]) AS 'Future',
    [Company]
FROM 
    [A_DW].[dbo].[NEW_ETL AccBalance]
WHERE
    [Company] = 'GAR' 
    AND NLPeriod = '3' AND NLYear = '2017'
GROUP BY
    [AccountCode], [ExpensesCode], [CostCentre], [NLYear], [NLPeriod], [Company]

This is Autoline database, and the data is a trial balance, so looks as follows:

+-----+------+-----+------+---+---------+---------+------+    
| 100 | 8000 | 700 | 2017 | 3 | 1000.00 | 2000.00 | 0.00 |
| 100 | 8001 | 700 | 2017 | 3 | 1500.00 | 4500.00 | 0.00 |
+-----+------+-----+------+---+---------+---------+------+

Result should 6500.00 (2000.00 + 4500.00)

Upvotes: 0

Views: 90

Answers (2)

S.Najjar
S.Najjar

Reputation: 65

The number of rows you are getting is equal to the number of distinct combination of : [AccountCode], [ExpensesCode], [CostCentre], [NLYear], [NLPeriod]

In case you need a single row, just remove those columns from the query and leave the sum columns.

Query can be :

SELECT 
    SUM([BroughtForward]) AS 'BF',
    SUM([CurrentPostings]) AS 'Current',
    SUM([FuturePostings]) AS 'Future'
FROM 
    [A_DW].[dbo].[NEW_ETL AccBalance]
WHERE
    [Company] = 'GAR' 
    AND NLPeriod = '3' AND NLYear = '2017'

Hope this helps.

Upvotes: 0

Steve Lovell
Steve Lovell

Reputation: 2564

Based on the sample data, your column ExpenseCode has multiple different values in it. If you want to collapse these two rows together, you need to decide what to do with that column. Here's one option: ignore it!

SELECT 
    [AccountCode],
    --[ExpensesCode], --comment it out, or delete entirely
    [CostCentre],
    [NLYear], [NLPeriod],
    SUM([BroughtForward]) AS 'BF',
    SUM([CurrentPostings]) AS 'Current',
    SUM([FuturePostings]) AS 'Future',
    [Company]
FROM 
    [A_DW].[dbo].[NEW_ETL AccBalance]
WHERE
    [Company] = 'GAR' 
    AND NLPeriod = '3' AND NLYear = '2017'
GROUP BY
    [AccountCode],
    --[ExpensesCode], -- also comment out here
    [CostCentre],
    [NLYear],
    [NLPeriod],
    [Company]

Upvotes: 1

Related Questions