【问题标题】:SQL Server pivot averageSQL Server 数据透视平均值
【发布时间】:2012-10-10 13:33:32
【问题描述】:

我有一个 Microsoft SQL 服务器数据透视查询,它获取每个类别的行数和每月列 1 到 12 的值的总和

我目前在查询中返回了13列,例如4月之后没有数据:

 Category  [1]   [2]   [3]   [4]   [5]   [6]   [7]   [8]   [9]   [10]   [11]   [12]
 -----------------------------------------------------------------------------------
 Food      150   200   0     125   null  null  null  null  null  null   null   null  
 Drink     140    0     90   115   null  null  null  null  null  null   null   null  

每个类别,我需要添加值的总和,以及忽略没有数据的月份的平均值。 对于上面的数据,我需要添加列:

 Sum   Average
 475    118.75
 345     86.25

我尝试了很多不同的方法,但我找不到方法。

【问题讨论】:

  • 您能发布您的原始查询、表结构和一些示例数据吗?可能有几种方法可以做到这一点,查看此信息会有所帮助。

标签: sql-server sql-server-2008 sum pivot average


【解决方案1】:

这个查询怎么样?

Select *
From
(
    Select ItemName as Itm, [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12] 
    From
    (
        Select ItemName, Month(EffectiveDate) as Mon, Val
            From Items

    ) as SourceTable
    Pivot
    (
        Sum(Val)
        For Mon in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
    ) as PivotTable
) A
Cross Apply (Select SUM(Val) as SumVal, AVG(Val) as AvgVal From Items i Where i.ItemName = a.Itm) b

看图:

http://s18.postimage.org/lwbovyy49/results.jpg

【讨论】:

  • 谢谢,这是一个干净的解决方案。
【解决方案2】:

我知道这看起来很愚蠢,但它可以解决问题。 :-)

Select Category,(isnull(f1,0)+isnull(f2,0)+isnull(f3,0)) as sumall,
isnull((isnull(f1,0)+isnull(f2,0)+isnull(f3,0)),1)/isnull(nullif((0+(isnull(nullif(isnull(f1,isnull(f1,0)),f1),1))+(isnull(nullif(isnull(f2,isnull(f2,0)),f2),1))+(isnull(nullif(isnull(f3,isnull(f3,0)),f3),1))),0),1) as avr
from MyTable

【讨论】:

  • 哦不! :p。太过分了!!
  • 抱歉,我的示例仅适用于 3 个“月”。复制/粘贴所有 f 字段以匹配 12 个月。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多