我有一个关于查询会计数据的问题。
例如,样本数据如下所示
表: Table_Test
Date Amount
2013-01-01 12.00
2013-01-02 13.00
输出应该是这样的:
Date Account Debit Credit
2013-01-01 Abccompany 12.00
2013-01-01 Vendorcompany 12.00
2013-01-02 Abccompany 13.00
2013-01-02 Vendorcompany 13.00
最初,我考虑使用union语句,因为输出序列可能不是很重要,示例sql显示如下
Select
Date as 'Date',
'Abccompany' as 'Account',
Amount as 'Debit',
'0' as credit
from Table_Test
union
select
Date as 'Date',
'VendorCompany' as 'Account',
'0' as 'Debit',
Amount as credit
from Table_Test
输出:
Date Account Debit Credit
2013-01-01 Abccompany 12.00
2013-01-02 Abccompany 13.00
2013-01-01 Vendorcompany 12.00
2013-01-02 Vendorcompany 13.00
但是在向我的PIC显示输出后,他似乎提到序列对他们非常重要是错误的。(用于导出到他们的系统中)
从我的想法出来的是使用T-Sql来操作这个可能提供像IsDebit和可能的row_number(第一个sql中的奇数,第二个sql上的偶数然后联合并且在它上面做了一些逻辑的标志)? ?)
有人能够告诉我如何解决这个问题吗?
答案 0 :(得分:2)
这样的事情应该有效:
Select
Date as 'Date', 'Abccompany' as 'Account', Amount as 'Debit', '0' as credit,
ROW_NUMBER() OVER (ORDER BY Date) * 2 as rn
from Table_Test
union all
Date as 'Date', 'VendorCompany' as 'Account', '0' as 'Debit', Amount as credit,
ROW_NUMBER() OVER (ORDER BY Date) * 2 + 1
from Table_Test
ORDER BY rn
虽然ORDER BY
条款中可能需要更多列来使事情明确无误(用你给出的有限例子告诉它有点棘手)
我也转而使用UNION ALL
,因为生成的结果集已经不同了。
答案 1 :(得分:1)
尝试在您的选择中使用此功能:
(ROW_NUMBER() OVER (ORDER BY Abccompany ASC))