简体   繁体   中英

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)

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM