我有以下工作查询,但我想知道是否可以使用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
的一个功能,它返回未聚合的任何字段的平均值吗?我可以取代SUM
或MIN
吗?最后,我如何确定这两个查询中的哪一个更有效?
答案 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