Sql server SQL Server中的嵌套分组依据
我有这个问题,你可以看到:Sql server SQL Server中的嵌套分组依据,sql-server,group-by,aggregate-functions,Sql Server,Group By,Aggregate Functions,我有这个问题,你可以看到: SELECT [LineId] ,[TestPackageId] ,[MaterialDescriptionId] ,isnull(sum([RequestQuantity]),0) as TotalMRC ,isnull(sum([QuantityDeliver]),0) TotalMIV ,isnull(sum([QuantityDeliverToMember]),0) totalIMIV ,isnull
SELECT
[LineId]
,[TestPackageId]
,[MaterialDescriptionId]
,isnull(sum([RequestQuantity]),0) as TotalMRC
,isnull(sum([QuantityDeliver]),0) TotalMIV
,isnull(sum([QuantityDeliverToMember]),0) totalIMIV
,isnull(sum([QuantityDeliver]),0) - isnull(sum([QuantityDeliverToMember]),0) as Warehouse
FROM
[SPMS2].[dbo].[ViewMTO2]
GROUP BY
[LineId], [TestPackageId], [MaterialDescriptionId]
结果是:
lindid tp matDes mrc miv imiv warehouse
101973 7927 61075 2 2 0 2
101991 8666 70721 1 1 0 1
102052 8751 71008 48 16 0 16
99626 8053 61075 0 0 0 0
问题是仓库,其值为false。仓库值应通过MaterialDescriptionId
计算仓库值,如下所示:TotalMIV totalIMIV
不是针对每一行([LineId]、[TestPackageId]、[MaterialDescriptionId])仅对于每个MaterialDescriptionId
而言,真正的结果是
lindid tp matDes mrc miv imiv warehouse
101973 7927 61075 2 2 0 2
101991 8666 70721 1 1 0 1
102052 8751 71008 48 16 0 16
99626 8053 61075 0 0 0 2
正如您所看到的,对于这两个项目,61075
应该是2。因为它是基于MaterialDescriptionId
计算的
在我的查询中如何做到这一点
这是我的viewmto2
结果(空值为零)
您可以使用单独的子查询来计算仓库:
SELECT
[LineId]
,[TestPackageId]
,[MaterialDescriptionId]
,isnull(sum([RequestQuantity]),0) as TotalMRC
,isnull(sum([QuantityDeliver]),0) TotalMIV
,isnull(sum([QuantityDeliverToMember]),0) totalIMIV
,(select isnull(sum(b.[QuantityDeliver]),0) from viewmto2 b where b.[MaterialDescriptionId] = a.[MaterialDescriptionId]) -
(select isnull(sum(b.[QuantityDeliverToMember]),0) from viewmto2 b where b.[MaterialDescriptionId] = a.[MaterialDescriptionId]) as Warehouse
FROM
[SPMS2].[dbo].[ViewMTO2] a
GROUP BY
[LineId], [TestPackageId], [MaterialDescriptionId]
看起来您需要一个子查询,通过
MaterialDescriptionId
计算分组仓库值:
SELECT
a.[LineId]
,a.[TestPackageId]
,a.[MaterialDescriptionId]
,isnull(sum(a.[RequestQuantity]),0) as TotalMRC
,isnull(sum(a.[QuantityDeliver]),0) TotalMIV
,isnull(sum([a.QuantityDeliverToMember]),0) totalIMIV
,b.Warehouse
FROM
[SPMS2].[dbo].[ViewMTO2] as a
INNER JOIN
(SELECT
MaterialDescriptionId, isnull((QuantityDeliver) - sum(QuantityDeliverToMember),0) as Warehouse
FROM [SPMS2].[dbo].[ViewMTO2]
GROUP BY MaterialDescriptionId) as b
ON
a.MaterialDescriptionId = b.MaterialDescriptionId
GROUP BY
a.[LineId], a.[TestPackageId], a.[MaterialDescriptionId], b.Warehouse
分组前是否可以添加
ViewMTO2
表格的样本数据by@Prdp请参阅update Dear当您说仓库
基于matDesc
时,会使您的结果集有点混乱。由于您的结果集基于所有3个字段,但您希望仓库仅基于1,因此您必须确保当用户在单独的行中看到2和2时,他们了解该matDesc
值的“总计”实际上是2而不是4。这对你的用户来说是清楚的吗?