sql语句查找总量

时间:2013-05-21 12:49:11

标签: sql oracle database

我正在尝试编写一个可以找到公司顶级客户端的SQL语句。顶级客户被定义为在所有公司的客户中购买了最多(总购买金额)的客户,而不仅仅是1次购买中的最大金额。我该如何解决这个问题呢?我对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”有用,我们非常感谢。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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