gpt4 book ai didi

mysql - 将 MySQL 简单查询转换为 SQL Server

转载 作者:行者123 更新时间:2023-11-29 06:33:26 24 4
gpt4 key购买 nike

我已经完成了MySQL简单查询,

SELECT 
acc_trans.VoucherNumber,
acc_trans.EntryDate,
acc_trans.Debit,
acc_trans.Credit,
@Balance:= round(@Balance,2) + acc_trans.Debit - acc_trans.Credit AS Balance
FROM acc_trans, (SELECT @Balance := 0) AS variableInit Where AccountName='Cash Account'
ORDER BY acc_trans.TransactionID ASC

输出

VoucherNumber  EntryDate    Debit         Credit      Balance
-------------------------------------------------------------
1 2019-01-12 0.00 2500.00 -2500.00
2 2019-02-12 0.00 15000.00 -17500.00
3 2019-02-12 0.00 1500.00 -19000.00
1 2019-02-12 4800.00 0.00 -14200.00

此查询在 MySQL 数据库中运行良好。我与 SQL Server 有相同的数据库。如何在 SQL Server 中执行此查询?

最佳答案

从 SQL Server 2008 开始,您可以使用 OVER子句:

输入:

CREATE TABLE acc_trans (
TransactionID int,
VoucherNumber int,
EntryDate date,
Debit numeric(20, 2),
Credit numeric(20, 2)
)
INSERT INTO acc_trans
(TransactionID, VoucherNumber, EntryDate, Debit, Credit)
VALUES
(1, 1, '2019-01-12', 0.00, 2500.00),
(2, 2, '2019-02-12', 0.00, 15000.00),
(3, 3, '2019-02-12', 0.00, 1500.00),
(4, 1, '2019-02-12', 4800.00, 0.00)

声明:

SELECT 
acc_trans.VoucherNumber,
acc_trans.EntryDate,
acc_trans.Debit,
acc_trans.Credit,
[Balance] = SUM(acc_trans.Debit - acc_trans.Credit) OVER (ORDER BY acc_trans.TransactionID ASC)
FROM acc_trans
WHERE AccountName = 'Cash Account'

输出:

VoucherNumber   EntryDate   Debit    Credit     Balance
1 2019-01-12 0.00 2500.00 -2500.00
2 2019-02-12 0.00 15000.00 -17500.00
3 2019-02-12 0.00 1500.00 -19000.00
1 2019-02-12 4800.00 0.00 -14200.00

注释:

如果你想用SELECT语句给SQL Server中的变量赋值,引用documentation的备注很重要:

SELECT @local_variable is typically used to return a single value into the variable. However, when expression is the name of a column, it can return multiple values. If the SELECT statement returns more than one value, the variable is assigned the last value that is returned.

A SELECT statement that contains a variable assignment cannot be used to also perform typical result set retrieval operations.

关于mysql - 将 MySQL 简单查询转换为 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55096738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com