2

我正在尝试编写一个可以找到公司顶级客户的 SQL 语句。顶级客户被定义为在公司所有客户中购买最多(总购买金额)的客户,而不仅仅是一次购买中的最大金额。我将如何解决这个问题?我对 SQL 没有太多经验,但到目前为止我所拥有的是:

SELECT CLIENT.CLIENTNO, CLIENT.CLIENT NAME, PURCHASE.AMOUNT
FROM PURCHASE, CLIENT
WHERE PURCHASE.CLIENTNO = CLIENT.CLIENTNO
GROUP BY CLIENT.CLIENTNO, CLIENT.CNAME, PURCHASE.AMOUNT;

这仅显示所有候选人的结果。既然我不是在寻找金额的最大值,而是在寻找最高支付客户的总和,我将如何开始?

如果有人可以回答,只是将其作为一个附加问题。我如何将我的一个表上的约束更改为限制为一组字符串?现在它是 varchar2(25) 但我希望它只对像“string”“string2”这样的帮助有效。

4

2 回答 2

2

尝试:

select CLIENTNO, CNAME
from (SELECT CLIENT.CLIENTNO, CLIENT.CNAME, rank() over (order by sum(PURCHASE.AMOUNT) desc) rnk
FROM PURCHASE join CLIENT on PURCHASE.CLIENTNO = CLIENT.CLIENTNO
GROUP BY CLIENT.CLIENTNO, CLIENT.CNAME)
where rnk = 1;

更新如果您想要购买金额的总和

select CLIENTNO, CNAME, spa PURCHASE_AMOUNT
from (SELECT CLIENT.CLIENTNO, CLIENT.CNAME, sum(PURCHASE.AMOUNT) spa,  rank() over (order by sum(PURCHASE.AMOUNT) desc) rnk
FROM PURCHASE join CLIENT on PURCHASE.CLIENTNO = CLIENT.CLIENTNO
GROUP BY CLIENT.CLIENTNO, CLIENT.CNAME)
where rnk = 1;
于 2013-05-21T12:56:16.110 回答
1

尝试这个

 Select c.ClientNo, c.CName Name, Sum(p.Amount)
 From Client c Join Purchase p 
    On p.clientNo = c.clientNo
 Group By c.CLientNo, c.ClientName
 Having Sum(p.Amount) =
       (Select Max(SumAmt)
        From (Select Sum(Amount) SumAmt
              From Purchase 
              Group By clientNo) z)

这个 sql 说

“为采购金额总和最大的特定客户选择客户编号、名称和采购金额总和。”

 Select c.ClientNo, c.CName Name, Sum(p.Amount) -- Select the clientNo, Name and sum 
 From Client c Join Purchase p 
    On p.clientNo = c.clientNo
 Group By c.CLientNo, c.ClientName              -- for the specific client whose 
 Having Sum(p.Amount) =                         -- sum of purchase amounts is 
       (Select Max(SumAmt)                      -- Largest 
        From (Select Sum(Amount) SumAmt         -- Sum of purchase amounts
              From Purchase 
              Group By clientNo) z)             -- for each client
于 2013-05-21T13:01:26.320 回答