简体   繁体   English

如何使用sql查询仅选择表底部的客户数据和总和作为行?

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

i have sql query.我有 sql 查询。 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.这是我的 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), ())

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?添加在分组和聚合之后发生的 HAVING 子句?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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