我有一个交易表,希望每行返回两行。交易表的每一笔交易都有一行。我想以以下日记帐输入格式返回交易日期和金额:
TransactionDate TransactionRef Transaction Amount
01/01/2019 12345 500.5
我还需要包括一个借方/贷方列,以使第一行过帐为正数,借方/贷方显示为'Db',然后返回的第二行将为负,借方/贷方显示为'Cr'< / p>
我需要查询交易表并返回以下值:
TransactionDate TransactionRef Transaction Amount Db/Cr
01/01/2019 12345 500.5 Db
01/01/2019 12345 -500.5 Cr
答案 0 :(得分:3)
另一个选择是交叉申请
Select A.TransactionDate
,A.TransactionRef
,B.TransactionAmount
,DrCr = case when sign(B.TransactionAmount)<0 then 'Cr' else 'Dr' end
From YourTable A
Cross Apply ( values ( TransactionAmount)
,( TransactionAmount*-1)
) B(TransactionAmount)
答案 1 :(得分:1)
使用UNION ALL:
sauce
答案 2 :(得分:1)
Select
coalesce(t1.transactiondate,t2.transactiondate) as transdate,
coalesce(t1.transactionref,t2.transactionref) as transref,
coalesce(t1.transactionamount,-1*ABS(t2.transactionamount)) as transamount
from tansaction t1 full outer join transaction t2
on 1 = 0
order by
TransactionRef,
transactiondate,
SIGN(t1.transactionamount)desc,
ABS(t2.transactionamount)
答案 3 :(得分:0)
使用联合查询:
SELECT TransactionDate, TransactionRef, [Transaction Amount], 'Db' AS [Db/Cr]
FROM yourTable
UNION ALL
SELECT TransactionDate, TransactionRef, -1.0*[Transaction Amount], 'Cr'
FROM yourTable;
这里的想法是上述联合查询的后半部分生成相同的记录,但交易金额为负,并带有Cr
作为标签。
答案 4 :(得分:0)
您可以使用UNION ALL
并从交易表中进行2个选择。
SELECT TransactionDate, TransactionRef, [Transaction Amount], 'Db' AS [Db/Cr] from table
UNION ALL
SELECT TransactionDate, TransactionRef, [Transaction Amount] * -1, 'Cr' AS [Db/Cr] from table
答案 5 :(得分:0)
如果原始表中的值始终为正,那么我将使用John解决方案的一种变体:
select t.TransactionDate, t.TransactionRef, v.drcr, v.TransactionAmount
from t Cross Apply
( values ('Cr', TransactionAmount),
('Dr', - TransactionAmount)
) v(drcr, TransactionAmount);