Sql 如何按客户获取前十大销售价格金额
我有一张客户信息表。此表中有四个字段。客户在表中出现了两次,但我想要客户的总销售价格 样本数据:Sql 如何按客户获取前十大销售价格金额,sql,sql-server,Sql,Sql Server,我有一张客户信息表。此表中有四个字段。客户在表中出现了两次,但我想要客户的总销售价格 样本数据: --------------------------------------------- | CustomerName Amount balance SalesPrice | -------------------------------------------- | user1 300 300 200 | --------------
---------------------------------------------
| 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
显示两次。我只想要销售价格的总和。我已经试过了,但是我在客户名称中获得了两次user1
。听起来你需要一个简单的分组
select top 10
CustomerName
Amount,
Balance,
TotalSalesPrice = sum(SalesPrice)
from YourTable
where CustomerName = 'user1'
group by CustomerName, Amount, Balance
order by TotalSalesPrice desc
这将获得每个
user1
的售价总和,该值在Amount
和Balance
中具有相同的值。如果这不是您想要的,那么您必须更好地解释,并提供更多的样本数据我认为简单的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';
这将起作用:
SELECT TOP 10 CustomerName
Amount as Amount,
Balance as Balance,
sum(SalesPrice) as SalesPrice
FROM Tablename
GROUP BY CustomerName, Amount, Balance
ORDER BY SalesPrice;
您可以使用窗口功能:
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;
或者,如果您不关心金额
和余额
是否来自同一行:
select CustomerName, min(Amount) as Amount, min(balance as balance), sum(SalesPrice) as total_SalesPrice
from t
group by CustomerName;
请用您真正使用的数据库标记您的问题。现在我修改了user1的记录,第一个记录量是300,第二个记录量是b300,SQL应该如何决定选择其中一个而忽略另一个呢?user1是相同的,但它会多次出现在表中我希望过滤它一次我不希望它出现两次而不是我希望我会计算user1销售价格你必须告诉我们公式。为什么售价是400,但余额仍然是300?如何计算?