如何获得客户的前10个销售价格金额

时间:2018-10-10 11:11:26

标签: sql sql-server

我有一个客户信息表。在此表中,有四个字段。客户两次出现在表中,但我想要该客户的总价。

样本数据:

function Calculatrice(a, b, op) {

  switch (op) {

    case '+':
      return a + b
      break;
    case '-':
      return a - b
      break;
    case '*':
      return a * b
      break;
    case '/':
      return a / b
      break;
  
  }

}
console.log(Calculatrice(5, 5, '+'));

我希望输出像

---------------------------------------------
| CustomerName   Amount  balance SalesPrice |
--------------------------------------------    
|  user1         300      300      200      |
--------------------------------------------
|  user2         300      300      200      |
--------------------------------------------
|  user3         b300     300      200      |
--------------------------------------------
|  user1         b300     300      200      |
--------------------------------------------

我不希望 --------------------------------------------- |CustomerName Amount balance SalesPrice | --------------------------------------------- | user1 300 300 400 | --------------------------------------------- 出现两次。我只想要销售价格的总和。我已经尝试过,但是两次获得user1的客户名。

4 个答案:

答案 0 :(得分:1)

听起来像您需要一个简单的分组依据

select top 10
       CustomerName   
       Amount,
       Balance,
       TotalSalesPrice = sum(SalesPrice)
from   YourTable
where  CustomerName = 'user1'
group by CustomerName, Amount, Balance
order by TotalSalesPrice desc

这将获得每个user1AmountBalance中具有相同值的SalesPrice的总和。如果那不是您想要的,那么您将不得不更好地解释并提供更多示例数据

答案 1 :(得分:0)

我认为简单的DISTINCT将基于示例数据:

select distinct t.CustomerName, t.Amount, t.balance, tt.SalesPrice 
from table t cross apply
     (select sum(t1.SalesPrice) as SalesPrice 
      from table t1
      where t1.CustomerName  = t.CustomerName 
     ) t1
where t.CustomerName = 'user1';   

答案 2 :(得分:0)

这将起作用:

SELECT TOP 10 CustomerName   
    Amount as Amount,
    Balance as Balance,
    sum(SalesPrice) as SalesPrice
FROM Tablename
GROUP BY CustomerName, Amount, Balance
ORDER BY SalesPrice;

答案 3 :(得分:0)

您可以使用窗口功能:

select CustomerName, Amount, balance, total_SalesPrice 
from (select t.*,
             row_number() over (partition by CustomerName order by (select null)) as seqnum,
             sum(t.SalesPrice) over (partition by CustomerName) as total_SalesPrice
      from t
     ) t
where seqnum = 1;

或者,如果您不在意amountbalance是否来自同一行:

select CustomerName, min(Amount) as Amount, min(balance as balance), sum(SalesPrice) as total_SalesPrice
from t
group by CustomerName;