2013-10-06 202 views
1

我正在使用MS SQL Server 2012SQL分組無法正常工作

我有一個查詢使用子查詢來創建一個顯示總計資產百分比的列。不過,我需要通過portfoliobasecode對總和列進行分組,如下所示。

我試過group by和partition沒有成功。與集團的結果是投資組合代碼正確組合,但總和仍然是所有投資組合的總和,而不是我想要的小計。

CashPCT

隨着分區我碰到下面的錯誤。我可以使用Top 1,但這並不能達到預期的效果。

ERROR

Msg 512, Level 16, State 1, Line 17 
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. 

error

使用TOP 1

top1

這可能是我把group by或在查詢錯了地方分區上。我需要一種方法來正確分組summedpct列。

下面是查詢: https://dl.dropboxusercontent.com/u/29851290/cashpercent.sql

下面是結果集和期望的結果。

CashPCT

與實際結果的問題是,它走的是總和所有PercentAssets和將它們放置在summedpct。

我想要的結果是這些百分比的資產按portfoliobasecode分組。注意在所需的結果集chambetr的summedp是2.66這是-457.50 + 460.18

+1

請修改您的問題,並顯示**完整**查詢作爲「代碼」塊(而不是圖像)。大多數人不喜歡「Dropbox」方法。這會讓問題更容易回答。 – BellevueBob

+0

看起來你已經回答了它,但將來我會粘貼查詢而不是鏈接。 –

回答

1

您不能使用「內聯」查詢,因爲它爲每個分區返回一行。所以,你需要我認爲的「加入」。也許這將工作:

USE APXFIRM 
--1. Establish the APX user session 
DECLARE @SessionGUID nvarchar(70) 
EXEC APXuser.pSessionInfoSetGuid @SessionGuid 

--2. Execute the query against the Appraisal accounting function 
DECLARE @ReportData varbinary(max) 
EXEC APXUser.pAppraisal 

-- Required Parameters. There may be other Optional Parameters. 
@ReportData = @ReportData out, 
@Portfolios = '@Test_Group', 
@Date = '10/02/2013' 

--3. Select the columns 

SELECT 
--Appraisal columns 
a.MarketValue, 
a.PercentAssets, 
--Security Columns 
s.SecuritySymbol, 
s.SecurityTypeCode, 

-- Portfolio Base columns 
b.PortfolioBaseCode, 
b.ReportHeading1, 
bb.summedpct 

--4. Join the Appraisal to additional views 
FROM APXUser.fAppraisal (@ReportData) a 
LEFT JOIN APXUser.vPortfolioBaseSettingEx b 
ON b.PortfolioBaseID = a.PortfolioBaseID 
LEFT JOIN APXUser.vSecurityVariant s 
ON s.SecurityID = a.SecurityID 


LEFT JOIN(
    SELECT PortfolioBaseCode 
     , SUM(PercentAssets) as summedpct 
    FROM APXUser.fAppraisal (@ReportData) aa 
    LEFT JOIN APXUser.vPortfolioBaseSettingEx b 
ON b.PortfolioBaseID = aa.PortfolioBaseID 
LEFT JOIN APXUser.vSecurityVariant s 
ON s.SecurityID = aa.SecurityID 

    WHERE s.SecTypeCode LIKe 'ca%' 

    AND s.SecTypeCode = aa.SecTypeCode 
    AND s.IsShort = aa.IsShortPosition 
    GROUP BY PortfolioBaseCode, SecurityTypeCode 
    ) bb 
on b.PortfolioBaseCode = bb.PortfolioBaseCode 
WHERE s.SecTypeCode LIKe 'ca%' 
AND s.SecTypeCode = a.SecTypeCode 
AND s.IsShort = a.IsShortPosition 
And summedpct >= @summedpct 
+0

謝謝你的嘗試。我收到各種錯誤,列不能在您添加的JOIN中綁定。多部分標識符「s.SecTypeCode」不能被綁定。無效的列名'PortfolioBaseCode'。等等......他們需要帶有別名前綴嗎? –

+0

我通過加入其他視圖來解決問題 –

+0

是的,這就是我的想法。沒有看到每個表的完整定義很難說。您可能需要將JOIN組件添加到派生表本身。 – BellevueBob