在 SQL Server 2005 中添加总行?
Posted
技术标签:
【中文标题】在 SQL Server 2005 中添加总行?【英文标题】:Adding a total row in SQL Server 2005? 【发布时间】:2019-05-21 18:33:43 【问题描述】:我有一个创建报告的脚本,但是我需要底部的总行。
在 SQL Server 2008 中,我想我会使用汇总,但我不知道如何在 SQL Server 2005 中执行此操作。
USE FEN
GO
SELECT
PMC.Store_ID,
PMC.Name,
SUM (PMC.[Net Sales] / 1000) AS 'Daily Sales',
SUM (PMCLY.[Net Sale LY] / 1000) AS 'Daily Sales LY',
CAST(100.0*(PMC.[Net Sales] - PMCLY.[Net Sale LY]) / PMCLY.[Net Sale LY] AS Decimal (10,2)) AS 'VAR % Vs LY',
SUM (PMCW.[Net Sales Week] / 1000) AS 'Daily Sales Week',
SUM (PMCLYW.[Net Sale Week LY] /1000) AS 'Daily Sales Week LY',
CAST(100.0*(PMCW.[Net Sales Week] - PMCLYW.[Net Sale Week LY]) / PMCLYW.[Net Sale Week LY] AS Decimal (10,2)) AS 'VAR % Vs LY'
FROM PMC_DailySalesReport AS pmc
JOIN PMC_DailySalesReportLY as pmcly on pmcly.Store_ID = pmc.Store_ID
JOIN PMC_DailySalesReportWeek as PMCW on pmcw.Store_ID = pmc.Store_ID
JOIN PMC_DailySalesReportLYWeek AS PMCLYW on PMCLYW.Store_ID = PMC.Store_ID
GROUP BY
PMC.Store_ID,
PMC.Name,
PMC.[Net Sales],
PMCLY.[Net Sale LY],
PMCLYW.[Net Sale Week LY],
PMCW.[Net Sales Week]
go
目的是将StoreID和Store Name的所有列的总和添加到表的底部
有什么想法吗?
【问题讨论】:
你可以有一个 UNION ALL 和第二个查询给你一行;总行数? @TT。您能否提供一些示例代码,因为我已经尝试过但没有任何运气。 【参考方案1】:我希望您可以添加一个UNION ALL
,它选择包含聚合的行而不进行任何分组,这应该为您提供所有行的数字:
-- your query above, and then:
UNION ALL
SELECT
'All' As Store_ID,
'All' As Name,
SUM (PMC.[Net Sales] / 1000) AS 'Daily Sales',
SUM (PMCLY.[Net Sale LY] / 1000) AS 'Daily Sales LY',
CAST(100.0*(PMC.[Net Sales] - PMCLY.[Net Sale LY]) / PMCLY.[Net Sale LY] AS Decimal (10,2)) AS 'VAR % Vs LY',
SUM (PMCW.[Net Sales Week] / 1000) AS 'Daily Sales Week',
SUM (PMCLYW.[Net Sale Week LY] /1000) AS 'Daily Sales Week LY',
CAST(100.0*(PMCW.[Net Sales Week] - PMCLYW.[Net Sale Week LY]) / PMCLYW.[Net Sale Week LY] AS Decimal (10,2)) AS 'VAR % Vs LY'
FROM PMC_DailySalesReport AS pmc
JOIN PMC_DailySalesReportLY as pmcly on pmcly.Store_ID = pmc.Store_ID
JOIN PMC_DailySalesReportWeek as PMCW on pmcw.Store_ID = pmc.Store_ID
JOIN PMC_DailySalesReportLYWeek AS PMCLYW on PMCLYW.Store_ID = PMC.Store_ID
考虑到在主查询中您有一些额外的 group by 字段,这些字段实际上并没有直接出现在选择中,这可能没有那么简单,但这是一般的想法。如果没有看到架构、示例数据和预期输出,就很难更精确(因为无法测试查询)。
【讨论】:
以上是关于在 SQL Server 2005 中添加总行?的主要内容,如果未能解决你的问题,请参考以下文章