0
我的影片由以下定義的兩個表:SQL服務器:對齊數據透視錶行
CREATE TABLE Portfolio.DailyStats
(Date date NOT NULL,
NAV int NOT NULL,
SP500 decimal(8,4) NULL,
R2K decimal(8,4) NULL,
NetExp decimal(8,4) NULL,
GrossExp decimal(8,4) NULL,)
GO
CREATE TABLE Portfolio.DailyPortfolio
(BbgID varchar(30) NOT NULL,
Ticker varchar(22) NULL,
Cusip char(9) NULL,
SecurityDescription varchar(50) NOT NULL,
AssetCategory varchar(25) NOT NULL,
LSPosition char(3) NULL,
Ccy varchar(25) NOT NULL,
Quantity int NULL,
AvgCost decimal(7,3) NULL,
PriceLocal decimal(7,3) NULL,
Cost int NULL,
MktValNet int NULL,
GLPeriod int NULL,
Beta decimal(4,2) NULL,
BetaExpNet int NULL,
BetaExpGross int NULL,
Delta decimal(4,2) NULL,
DeltaExpNet int NULL,
DeltaExpGross int NULL,
Issuer varchar(48) NOT NULL,
Country varchar(30) NOT NULL,
Region varchar(20) NOT NULL,
Sector varchar(30) NOT NULL,
Industry varchar(48) NOT NULL,
MktCapCategory varchar(24) NULL,
MktCapEnd int NULL,
Date date NOT NULL,
PortfolioID AS BbgID+LSPosition+ Convert(varchar(8),Date,112) Persisted
Primary Key)
GO
我試圖創造一個我可以看看PNL貢獻爲每間發行機構按年,其中每年表示由一列組成。 PNL貢獻定義爲該年度每年/ AVG(NAV)的SUM(GLPeriod)。舉個例子,我的最終輸出應該是這樣的:
Issuer| 2015| 2016| 2017|
:-----|-----|-------|-------|
Issuer A| -0.012550646| -0.| NULL|
Issuer B| -0.00701487| -0.000759621| -0.004905285|
Issuer C| NULL| -0.002270388| -0.003730801|
而是通過電流輸出是這樣的:
Issuer| 2015| 2016| 2017|
:-----|-----|-------|-------|
Issuer A| NULL| -0.| NULL|
Issuer A| -0.012550646| NULL| NULL|
Issuer B| NULL| NULL| -0.004905285|
Issuer B| NULL| -0.000759621| NULL|
Issuer B| -0.00701487| NULL| NULL|
Issuer C| NULL| NULL| -0.003730801|
Issuer C| NULL| -0.002270388| NULL|
在這裏,我使用的代碼:
CREATE VIEW Portfolio.ContributionByYear
AS
WITH a
AS
(
SELECT Issuer, SUM(GLPeriod) PNL, DATEPART(yyyy, Date) Year
FROM Portfolio.DailyPortfolio
GROUP BY Issuer, DATEPART(yyyy, Date)
)
,
b AS
(
SELECT AVG(CAST(NAV AS BIGINT)) AvgNAV, DATEPART(yyyy, Date) Year
FROM Portfolio.DailyStats
GROUP BY DATEPART(yyyy, Date)
),
c AS
(
SELECT a.Issuer, a.PNL, a.Year, b.AvgNAV , CONVERT(decimal (15,3),
a.PNL)/CONVERT(decimal (15,3), b.AvgNAV) [Contrib]
FROM a
JOIN b
ON a.Year = b.Year
)
SELECT Issuer, [2015],[2016],[2017]
FROM c
PIVOT
(
SUM(c.Contrib)
FOR [Year] IN ([2015],[2016],[2017])
) AS PivotTable
GO
另一個問題我有這個代碼是我在數據透視表中使用SUM聚合函數,但實際上並沒有添加任何東西。它只是將數據從行移動到列。但是,我似乎無法在不使用某種聚合函數的情況下調整數據。
感謝。不能相信這是多麼簡單。爲什麼這兩列使用額外的行創建這個問題? – MilesToGoBeforeISleep
@MilesToGoBeforeISleep - 在數據透視源數據中不應該有任何額外的列,否則它會考慮那些也是爲了旋轉這就是爲什麼看到'NULL'..你可以選擇'a.PNL'和'b.AvgNAV'列在最後'選擇'你的情況不需要.. –