【发布时间】:2020-03-18 19:43:28
【问题描述】:
我已经能够使用下面的 SQL 查询给我 4 行数据
SELECT 'Sales Order ' as Type, Format(Sum(T1.C_NetAmountLessDiscount),
'#.00') As NetAmount, Format(Sum(T1.C_MarginAmount), '#.00') As
MarginAmount, Format(Sum(T1.C_MarginAmount)/Sum(T1.C_NetAmountLessDiscount),
'#.00%') As Margin
From T_SalesOrder as T1
Where cast(T1.C_Date as Date) = cast(getdate() as Date) AND T1.C_OrderType
!= 'BK' AND T1.C_OrderType != 'INV'
Union
SELECT 'Despatch Notes ' AS Type, Format(Sum(T1.C_NetAmountLessDiscount),
'#.00') As NetAmount, Format(Sum(T1.C_MarginAmount), '#.00') As
MarginAmount, Format(Sum(T1.C_MarginAmount)/Sum(T1.C_NetAmountLessDiscount),
'#.00%') As Margin
From T_SalesDeliveryNote as T1
Where cast(T1.C_Date as Date) = cast(getdate() as Date) AND T1.C_Order is
null AND T1.C_BillingStatus = '0'
Union
SELECT 'Invoices ' AS Type, Format(Sum(T1.C_NetAmountLessDiscount), '#.00')
As NetAmount, Format(Sum(T1.C_MarginAmount), '#.00') As MarginAmount,
Format(Sum(T1.C_MarginAmount)/Sum(T1.C_NetAmountLessDiscount), '#.00%') As
Margin
From T_SalesInvoice as T1
Where cast(T1.C_Date as Date) = cast(getdate() as Date) And
T1.C_DeliveryNote is null And T1.C_SourceOrder is null and T1.C_InvoiceType
= '0'
Union
SELECT 'Credit Notes ' AS Type, Format(Sum(T1.C_NetAmountLessDiscount), '-
#.00') As NetAmount, Format(Sum(T1.C_MarginAmount), '-#.00') As
MarginAmount, Format(Sum(T1.C_MarginAmount)/Sum(T1.C_NetAmountLessDiscount),
'#.00%') As Margin
From T_SalesCreditNote as T1
Where cast(T1.C_Date as Date) = cast(getdate() as Date)
这为我提供了我需要的订单明细,但我还希望有一个总计行来对每一列求和。
如果我将上面的 sql 查询插入到下面
Select 'Grand Total', Sum(CAST(NetAmount AS float)), Sum(CAST(MarginAmount
AS float)),null
From
(
-----Above SQL Query in Here
)tbl
我得到一个包含正确总数但没有细分行的单行。
我该怎么做才能显示每种类型的四行和底部的总计行。
【问题讨论】:
-
你用的是什么关系型数据库?
-
嗨 JNevill,这是使用 MS SQL Server 2012
-
也许你可以添加到一个临时表来保存四行并将四行结果评估为最后一行。然后您可以返回临时表
-
看看 GROUPING SETS... 例如stackoverflow.com/questions/56827331/…
-
嗨约翰,这给了我我需要的东西,谢谢。只需要能够在类型列中添加一个名称(即总计),但似乎找不到这样做的方法。
标签: sql sql-server sql-server-2012