I have the following working query but I was wondering if I could simplify it using 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
I can get the first 3 columns easily:
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;
but I wasn't sure how to get that fourth (AVG(TheSpot) AS [Index Level]
) column. So I played around a bit and found that the following works:
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;
But I don't understand why this is giving me the average of the theSpot
column? Is that a feature of PIVOT
that it returns the average for any field not aggregated? Could I have gotten the SUM
or MIN
instead? Lastly how would I ascertain which of these two queries is more efficient?