如何计算每行的总计?
这样,如果我有一个 成本 列,并且每行中的数据都比我想要在末尾计算其总和,按特定列分组并满足特殊情况。
我试过了:
SELECT
[SchemeName]
,SUM(CAST([SchemeCost] as INT)) as COST
,[SchemeHolderName]
,[SchemeApprovedBy]
FROM [WMS_MCP].[dbo].[Schemes]
Where SchemeHolderName like '%'+ 'Hussain' +'%'
Group By SchemeCost,SchemeName,SchemeHolderName,SchemeApprovedBy
UNION ALL
SELECT
''
,SUM(CAST([SchemeCost] as INT)) as COST
,''
,''
FROM [WMS_MCP].[dbo].[Schemes]
Where SchemeHolderName like '%'+ 'Hussain' +'%'
Group By SchemeCost,SchemeName,SchemeHolderName,SchemeApprovedBy
但它没有产生所需的输出,我希望最后一行为空,只有TOTALCOST。
答案 0 :(得分:0)
从union
中的第二个select语句中删除Group by子句 SELECT
[SchemeName]
,SUM(CAST([SchemeCost] as INT)) as COST
,[SchemeHolderName]
,[SchemeApprovedBy]
FROM [WMS_MCP].[dbo].[Schemes]
Where SchemeHolderName like '%'+ 'Hussain' +'%'
Group By SchemeCost,SchemeName,SchemeHolderName,SchemeApprovedBy
UNION ALL
SELECT
''
,SUM(CAST([SchemeCost] as INT)) as COST
,''
,''
FROM [WMS_MCP].[dbo].[Schemes]
Where SchemeHolderName like '%'+ 'Hussain' +'%'