PIVOT会自动取非聚合列的平均值吗?

时间:2014-08-21 07:28:27

标签: sql-server join pivot

我有以下工作查询,但我想知道是否可以使用PIVOT简化它:

SELECT P.Date, 
       P.OI AS [Total Puts], 
       C.OI AS [Total Calls], 
       P.[Index Level]
FROM (SELECT Date, 
             SUM(OpenInterest) AS OI, 
             AVG(TheSpot) AS [Index Level]
      FROM Fullstats            
      WHERE theType = 'P'            
        and Code = 'ALSI'            
      GROUP BY Date) AS P
JOIN (SELECT Date, 
             SUM(OpenInterest) AS OI
      FROM Fullstats            
      WHERE theType = 'C'            
        and Code = 'ALSI'            
      GROUP BY Date) AS C            
ON P.Date = C.Date
ORDER BY Date 

我可以轻松获得前3列:

SELECT [Date], 
       P AS [Total Puts],
       C AS [Total Calls]
FROM (SELECT Date, 
             OpenInterest, 
             theType 
      FROM FullStats 
      WHERE Code = 'ALSI') AS SourceTable
PIVOT
(
    SUM(OpenInterest)
    FOR theType IN (P, C)
) AS PivotTable 
ORDER BY Date;

但我不确定如何获得第四个(AVG(TheSpot) AS [Index Level])列。所以我玩了一下,发现以下工作:

SELECT [Date],
       P AS [Total Puts],
       C AS [Total Calls],
       theSpot       
FROM (SELECT Date, 
             OpenInterest, 
             theType, 
             theSpot 
      FROM FullStats 
      WHERE Code = 'ALSI' AND theType <> 'F') AS SourceTable
PIVOT
(
    SUM(OpenInterest)
    FOR theType IN (P, C)
) AS PivotTable
ORDER BY Date;

但我不明白为什么这会给我theSpot列的平均值?这是PIVOT的一个功能,它返回未聚合的任何字段的平均值吗?我可以取代SUMMIN吗?最后,我如何确定这两个查询中的哪一个更有效?

1 个答案:

答案 0 :(得分:1)

不汇总不会给你“TheSpot”的平均值可能是你所获得的价值来自一个聚合的视图,不知怎的,你为此幸运。查看下面的查询,了解获得平均值的方法。

create table pivot_demo (
    Id int identity(1,1)
    , Value1 decimal
    , Value2 decimal
    , SetKey int)

insert pivot_demo (Value1, Value2, SetKey) values 
(10,10,1),
(20,20,1),
(30,30,1),
(40,40,1),
(50,50,1),
(60,60,1),
(10,10,2),
(20,20,2),
(30,30,2),
(40,40,3),
(50,50,3),
(60,60,3)

select value2, [1], [2], [3] from (
    select value1, avg(value2) value2, setkey 
    from demo..pivot_demo
    group by Value1, SetKey) sub
pivot (sum(value1) for setkey in ([1], [2], [3])) piv