概述:
比较各种账户的代理商的日常交易,找出代理商和公司持股之间的差异,仅显示新的;当前交易中的代码,但不是之前的交易。
目标:
按最高频率的代码(即苹果)对交易进行排序。
当前代码:
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 :(得分: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