简体   繁体   中英

How to select only customer data and sum of that at bottom of table as row using sql query?

i have sql query. this query is providing me a lots of record of customer and that voucher and order subtotal but i want sum of debit and credit row and credit and debit column sum at bottom position of table.

so guide me how can i achieve this table using by query.

this is my sql query.

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), ())

i have attached my output image.在此处输入图片说明

in my image i got this result but that is very messy process so give me a proper solution for this.

Add a HAVING Clause which happens after the grouping and aggregating?

....
GROUP BY GROUPING SETS ((CustomerId),(OrderDate, VoucherType, VoucherNo), ())
HAVING VoucherType Is Null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM