我有SQL查詢。 這個查詢爲我提供了大量的客戶記錄和該憑證和訂單小計,但我想借記和貸記行以及貸方和借記欄總和在表格的底部位置。如何僅使用sql查詢選擇客戶數據和表格底部的總和作爲行?
所以引導我如何通過查詢來實現此表。
這是我的sql查詢。
declare @Credit decimal(18,2)
declare @Debit decimal(18,2)
select @debit= SUM(sd.SubTotal)
from SalesOrderDetails sd
left join SalesOrder so
on sd.SalesOrderId = so.SalesOrderId
select @credit = SUM(Amount) from Vouchers
SELECT CustomerId,
OrderDate,
VoucherType,
VoucherNo,
SUM(Debit) as Debit,
SUM(Credit) as Credit
FROM (SELECT so.CustomerId,
so.OrderDate ,
'Sales' As VoucherType,
'' AS VoucherNo,
a.Total As Debit
, NULL As Credit
from SalesOrder so
inner join (
SELECT SalesOrderId,
sum(SubTotal) AS Total
FROM SalesOrderDetails
group by SalesOrderId
)as a
on so.SalesOrderId = a.SalesOrderId
UNION ALL
SELECT V.CustomerId
,v.VoucherDate As OrderDate
, 'Receipt' AS VoucherType
,v.VoucherNumber AS VoucherNo
,NULL AS Debit
,v.Amount AS Credit
from Vouchers v
) ledger
GROUP BY GROUPING SETS ((CustomerId),(OrderDate, VoucherType, VoucherNo),())
我附上了我的輸出圖像。
在我的圖片我得到了這個結果,但這是非常混亂的過程,所以給我一個適當的解決方案。
如果你自己寫了這個查詢那麼我認爲你有足夠的能力來達到你想要 – Luftwaffe
是的,我從互聯網上幫助這個寫什麼。但我想要其他查詢是短的,我可以實現這個輸出。 –