繁体   English   中英

SQL查找总交易金额最大的Top Customer,列出交易,并在底部的行中合计所有交易

[英]SQL Find Top Customer with greatest total transaction amount, list transactions, and total all transactions in row at bottom

来自交易表的样本数据..

例子

transaction_id 客户ID 交易金额 交易位置
600 66 504.57 美元 加利福尼亚
601 47 367.14 美元 弗吉尼亚
602 36 $756.00 密歇根州
603 63 364.62 美元 德克萨斯州

这是问题:

列出总交易金额最高的前 1 个客户的交易,结果显示客户完成的所有交易,最后一行显示客户完成的所有交易的总金额。 例如:输出应采用以下格式:

transaction_id 交易金额
1 50.06
5 298.45
20 400.73
31 75.48
50 1300.15
-------------------------- ------------------
Total_Transactions_Amount 2124.87

我正在解决这个问题。 我在想也许需要自我加入?

/*SELECT t1.transaction_amount, t1.transaction_id
FROM Transactions t1
INNER JOIN Transactions t2
ON t1.transaction_id = t2.transaction_id
...? */

我知道我需要使用某种排名函数或行号函数??,或类似的东西。 这部分真的需要帮助。

总而言之,我知道我的代码需要对客户 ID 进行分区,并且需要某种方式来排名和输出排名第一的客户。

我也知道我需要一个 ROLLUP 函数来计算下面一行的总数,但我还没有谈到我的解决方案的那一部分。 这就是我到目前为止所拥有的。

我发现客户 #50 是 #1 客户,所以现在我能够对客户 ID 进行分区并输出所有交易和 Total_Transactions_Amount。

SELECT customer_id, transaction_id, transaction_amount, 
 SUM(transaction_amount) 
    OVER (Partition BY customer_id) AS Total_Transactions_Amount 
 FROM Transactions
 WHERE customer_id = 50
 GROUP BY customer_id, transaction_id, transaction_amount
 ORDER BY transaction_amount DESC, customer_id, transaction_id

您的最后一个查询实际上并没有多大意义。

首先你需要找到总金额最高的客户:

select customer_Id, sum(transaction_amount)
from Transactions
group by customer_id
order by sum(transaction_amount) desc; 

我们只需要 top(1),因此:

select top(1) customer_Id, sum(transaction_amount)
from Transactions
group by customer_id
order by sum(transaction_amount) desc; 

而且我们在这里真的不需要 sum(),只需要 customer_id,因此:

select top(1) customer_Id
from Transactions
group by customer_id
order by sum(transaction_amount) desc; 

到目前为止一切顺利,如果我们知道 customer_id,我们会写:

SELECT transaction_id, sum(transaction_amount) as transaction_amount 
 FROM Transactions
 WHERE customer_id = 50
 GROUP BY transaction_id
 ORDER BY transaction_id
 with rollup;

我们实际上在前一个查询中发现了 customer_id,因此将它们连接起来:

SELECT transaction_id,
       SUM(transaction_amount) AS transaction_amount
FROM Transactions
WHERE customer_id IN
      (
          SELECT TOP (1)
                 customer_Id
          FROM Transactions
          GROUP BY customer_id
          ORDER BY SUM(transaction_amount) DESC
      )
GROUP BY transaction_id
ORDER BY transaction_id
with rollup;

顺便说一句,使用 IN () 是因为可能有多个客户具有相同的总 transaction_amount 并且在这种情况下您可能希望与 tie 一起使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM