使用 SQL Select 语句进行 Null 计算

mah*_*esh 5 sql t-sql sql-server

我有下表

Input           Output
---------------------------------
12.22           
                2.22
Run Code Online (Sandbox Code Playgroud)

如果我通过以下 Sql 语句:

按输入、输出从库存组中选择输入、输出、余额=总和(输入 - 输出)

所以输出是:

Input            Output       Balance
--------------------------------------
12.22            NULL         NULL
NULL             2.22         NULL
Run Code Online (Sandbox Code Playgroud)

如果我想要如下输出:

Input            Output       Balance
--------------------------------------
12.22                         12.22
                 2.22         10.00
Run Code Online (Sandbox Code Playgroud)

什么是 SQL Transact 语句?

我的表结构如下:

companyID   int
transID     int    -- Primary Key (Auto Increment)
Date        datetime
particulars varchar
input       decimal
output      decimal
Run Code Online (Sandbox Code Playgroud)

注意:- 我在这里对输入和输出列应用了Group By函数,这没有什么区别,因为有 transID 列是自动增量的,因此它应该显示表的所有行。

arc*_*ain 3

我想这可能对你有用。首先,这是我定义测试表和测试数据的方式:

declare @stock table (
  transId int not null identity(1,1), 
  [date] date not null, -- use datetime if not using SQL Server 2008
  input decimal(7,2) null, 
  [output] decimal(7,2) null
);

insert into @stock values
('1/23/2011', 12.22, null),
('1/23/2011', null, 2.22),
('1/24/2011', 16, null),
('1/24/2011', 3.76, null),
('1/24/2011', null, 5.50);
Run Code Online (Sandbox Code Playgroud)

这是我用来生成您在问题中指定的结果的选择。该查询按交易 ID 顺序生成给定日期所有交易的总计。如果您想计算多天的总计,请注释掉该AND b.[date] = a.[date]行。

select 
  [date],
  input = isnull(input,0), 
  [output] = isnull([output],0),
  balance = (isnull(input,0)-isnull([output],0)) +
        isnull((
          select 
            sum((isnull(input,0)-isnull([output],0)))
          from @stock b
          where b.transId < a.transId
          and b.[date] = a.[date] -- comment this for totals over multiple dates
        ),0)
from @stock a
order by transId;
Run Code Online (Sandbox Code Playgroud)

该查询给出:

date        input   output  balance
2011-01-23  12.22   0.00    12.22
2011-01-23   0.00   2.22    10.00
2011-01-24  16.00   0.00    16.00
2011-01-24   3.76   0.00    19.76
2011-01-24   0.00   5.50    14.26
Run Code Online (Sandbox Code Playgroud)

作为脚注,由于每笔交易的运行总值始终相同,因此我建议在表中添加一个余额列,并在插入交易行时计算余额列的值。这样,您只需查看最后一笔交易的余额即可确定要插入的交易的余额应该是多少。