2012-10-16 60 views
0

概述:
比較作爲各種賬戶代理的產品的日常交易,以發現代理和公司持股之間的差異,只顯示新增內容;代碼在當前的交易,但不是以前的交易。如何按頻率排序而不進行彙總?

目標:
用最高頻率的代碼(即蘋果)對交易進行排序。

目前代碼:

SELECT 
    Count(CurrentTrade.Code) AS CountOfCode, 
    CurrentTrade.portfolio_code, 
    CurrentTrade.Type, 
    CurrentTrade.Code, 
    sum(CurrentTrade.Custodian_holding) AS AgentHolding, 
    sum(CurrentTrade.Company_holding) AS CompanyHolding, 
    sum(CurrentTrade.Difference) AS TotalDifference 
FROM 
    CurrentTrade 
    LEFT JOIN PrevTrade 
    ON CurrentTrade.Company_holding = PrevTrade.Company_holding 
WHERE 
    PrevTrade.Company_holding) Is Null 
GROUP BY CurrentTrade.Code, CurrentTrade.portfolio_code, CurrentTrade.Code, CurrentTrade.Type 
ORDER BY count(CurrentTrade.Code); 

當前結果:

CountOfCode  account_code  Type  Code  AgentHodling  CompanyHolding  TotalDifference 
1     acc001049  prod  mango  2500     0  2500 
1     acc636903  prod  mango  481081.29  481081.285  0.01 
1     acc179186  prod  mango  453639.61  511285.81  -57646.2 
1     acc179185  prod  mango  2775    2650  125 
1     acc170001  prod  grapes  0      1500  -1500 
1     acc170000  prod  grapes  2500  0  2500 
1     acc107104  prod  apple  49797.22  49797.28  -0.06 
1     acc107103  prod  apple  0  -0.06  0.06 
1     acc107102  prod  apple  2000  500  1500 
1     acc107101  prod  apple  0  1500  -1500 
1     acc001189  prod  apple  0  1090.513  -1090.513 

參考:

我收到了一個答案(Order by count not sorting correctly - SQL (MS Access 2007)),所以這是一個跟進。

問:

是否有可能通過頻率命令沒有聚集所有的結果,並仍然顯示由包括相關的賬號最高頻率(蘋果,芒果,葡萄)命令?
如果對訂單使用金額「在ORDER BY中不能有聚合函數」,所以我不確定我能否做到這一點,並且仍然保持帳號分開?

回答

0

拉出ORDER BY條款爲外部查詢和內部查詢將計算頻率,具體如下:

SELECT * FROM (
SELECT 
    Count(CurrentTrade.Code) AS CountOfCode, 
    CurrentTrade.portfolio_code, 
    CurrentTrade.Type, 
    CurrentTrade.Code, 
    sum(CurrentTrade.Custodian_holding) AS AgentHolding, 
    sum(CurrentTrade.Company_holding) AS CompanyHolding, 
    sum(CurrentTrade.Difference) AS TotalDifference 
FROM 
    CurrentTrade 
    LEFT JOIN PrevTrade 
    ON CurrentTrade.Company_holding = PrevTrade.Company_holding 
WHERE 
    PrevTrade.Company_holding) Is Null 
GROUP BY CurrentTrade.Code, CurrentTrade.portfolio_code, CurrentTrade.Code, CurrentTrade.Type 
) ORDER BY CountOfCode ASC 
+0

感謝您的解決方案!我最終創建了兩份報告1)沒有portfolio_code作爲總結,按正確的順序排列,2)用投資組合代碼獲取詳細信息。 – Lance96