accounts table
----------------
id name
10 ABC Company
11 XYZ Company
12 LMN Company
13 EFG Company
14 JKL Company
.. ...........
.. ...........
accounts_opportunities table
-----------------------
id opportunity_id account_id deleted
1 1 11 0
2 2 11 0
3 3 12 0
4 4 12 0
5 5 13 0
6 6 14 0
. . .. .
. . .. .
opportunities table
-----------------
id name amount
1 Opp 1 100
2 Opp 2 50
3 Opp 3 500
4 Opp 4 600
5 Opp 5 200
6 Opp 6 1000
我正在尝试从上表中选择前20个帐户。我写了以下查询 即,
SELECT TOP 20 COUNT(*) as number_of_opportunities,
(
SELECT accounts.name
FROM accounts
WHERE accounts.id=accounts_opportunities.account_id
) as account_name
FROM accounts_opportunities
JOIN opportunities ON opportunities.id = accounts_opportunities.opportunity_id
WHERE accounts_opportunities.deleted != '1'
GROUP BY accounts_opportunities.account_id
ORDER BY number_of_opportunities DESC
以上查询提供以下输出;
Account name Number of Opportunities
------------ -----------------------
ABC Company 3
XYZ Company 2
LMN Company 2
EFG Company 1
JKL Company 1
XYZ和LMN具有相同的数字机会,但如果我计算XYZ的总数量机会小于LMN总数量。此外,JKL的数量高于EFG。
我的问题是如何从 number_of_opportunities 然后总机会金额订购此查询。有人可以给我一个指南..
预期输出
Account name Number of Opportunities
------------ -----------------------
ABC Company 3
LMN Company 2
EFG Company 1
JKL Company 1
XYZ Company 2
答案 0 :(得分:1)
试试这个:
SELECT TOP 20 a.name, COUNT(*) AS [Number of Opportunities]
FROM accounts AS a
INNER JOIN accounts_opportunities AS ao ON a.id = ao.account_id
INNER JOIN opportunities AS o ON o.id = ao.opportunity_id
WHERE ao.deleted != 1
GROUP BY a.id, a.name
ORDER BY COUNT(*) DESC, SUM(amount) DESC
因此,您可以使用SUM(amount)
在ORDER BY
子句中添加DESC
。如果COUNT(*)
出现问题,我们会在其他帐户中添加金额较高的帐户。