简体   繁体   English

SQL Server:对列求和

[英]SQL Server : sum a column

I have tried everything I could to get the Current column added up. 我已尽一切努力将“ Current列加起来。 'BF', 'Current' and 'Future' should all equal zero and I just need a quick check to verify it. “ BF”,“ Current”和“ Future”都应为零,我只需要快速检查一下即可进行验证。

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: 这是Autoline数据库,数据是试用余额,因此如下所示:

+-----+------+-----+------+---+---------+---------+------+    
| 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) 结果应为6500.00(2000.00 + 4500.00)

Based on the sample data, your column ExpenseCode has multiple different values in it. 根据示例数据,您的列ExpenseCode包含多个不同的值。 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] 您获得的行数等于以下各项的不同组合数: [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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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