MS查询计算和分组问题Excel 2010数据透视表

首先在这里,你们都帮了我很多。

我的问题是我在Excel 2010中使用ODBC连接到SQL Server 2008 R2数据库来构build销售委员会。 我有两个行组和两个列组。 团体在父母的孩子的顺序。

行组是产品等级和产品。 列组是date和地区(东方和西方)。 价值是按地区的产品价格。 我试图在每个地区组(东部价格 – 西部价格)之后加上一个小计。 有时候只有一个地区被报告,所以如果是西方的话,就不应该存在小计。

我已经尝试了计算项目的组合,这几乎可以工作,但为每个区域添加了一列。 或者在SQL Server中进行工作,除了产品等级分组以外,它几乎都可以在每个父组中传播所有产品。 我宁愿使这个工作在SQL Server的显而易见的原因,我是新的在Excel中构build数据。 我敢肯定,这是非常简单的东西我错过了。 任何帮助将非常感激。

;with t as ( select info.protype, info.product, case when info.pricecode = 'x' then 'East' else 'West' end as Region, SUM(isnull(info.price,0)) as Price, case when r1.product=r2.product then SUM(x.price-y.price) else 0 end as Diff, info.effectdate from (select protype, product, pricecode, price, effectdate from prc_table where pricecode in ('x','y') and protype = 'z') as info left join prc_table r1 on info.protype = r1.protype and info.product = r1.product and info.effectdate = r1.effectdate and r1.pricecode = 'x' left join prc_table r2 on info.protype = r2.protype and info.product = r2.product and info.effectdate = r2.effectdate and r2.pricecode = 'y' where info.effectdate >= DATEADD(MM, -3, GETDATE()) and info.effectdate <= GETDATE() group by info.effectdate, info.protype, info.product, r1.product, r2.product, info.pricecode, r1.price, r2.price ) select c.codedesc as [Grade], r.product as [Product], r.Region as [Region], r.Price as [Price], r.Diff as [EW], r.effectdate as [Date] from tr inner join pro_item i on r.protype = i.protype and r.product = i.product inner join pro_duct p on i.protype = p.protype and i.product = p.product and i.1 = p.1 (product grade join) inner join xxx_codes c on p.desc3 = c.code and c.prefix = 'xxx' where i.protype = 'z' and i.loc = 'loc' and p.desc4 = '' and i.branch = 'm' order by r.effectdate desc, codedesc, product 

我得到你想要做的。 而且你在正确的轨道上来计算你的sql中的差异,因为不可能在数据透视表中显示/隐藏小计,这取决于它是东/西还是东。 所以在SQL中这样做是好的。 我认为你的查询中有一些devise缺陷试图将差异放在单独的列中。

问题在于,你如何在数据透视表中显示它? 如果您在数据透视表中同时使用Price和Diff作为您的值字段,则会完全打乱布局。 你只想要一个价值领域 – 价格。 而你希望东,西和差异成为你的列标题,所以它们都应该是你的数据中的区域。

因此,在你的sql中,获得你所做的等级,产品,地区,价格和date,把它放在临时表中,然后INSERT INTO到差异logging的临时表,其中region ='Diff'和Price =实际的差异值,在该产品和生效date存在东部和西部的logging。

你的输出应该是这样的:

 Grade Product Region Price Effdt A P1 East 1.5 31-Oct-14 A P2 East 3 31-Oct-14 B P3 East 5 31-Oct-14 B P4 East 2.44 31-Oct-14 C P5 East 3.67 31-Oct-14 C P6 East 10.3 31-Oct-14 B P3 West 5.5 31-Oct-14 B P4 West 2.7 31-Oct-14 C P5 West 3.8 31-Oct-14 C P6 West 10.7 31-Oct-14 A P1 East 1.5 30-Nov-14 A P2 East 3 30-Nov-14 B P3 East 5 30-Nov-14 B P4 East 2.44 30-Nov-14 C P5 East 3.67 30-Nov-14 C P6 East 10.3 30-Nov-14 B P3 Diff -0.5 31-Oct-14 B P4 Diff -0.26 31-Oct-14 C P5 Diff -0.13 31-Oct-14 C P6 Diff -0.4 31-Oct-14 

您只在适用的地方插入不同的行,所以当您旋转此数据时,它将显示east + west + diff或东或东或差异。

看起来你用sql编写上面的查询非常舒服,所以你应该能够实现这一点。 如果你在遇到问题时遇到问题,我会去看看。

干杯