简体   繁体   English

SUM的多个不同值

[英]Multiple Distinct Values with SUM

i have a table which Data is like 我有一张桌子,数据就像

userID      name        amount   Date
     1        mark        20     22-10
     1        mark        30     22-10
     2        kane        50     22-12  
     2        kane        60     22-12
     3        mike        60     22-10 

Date is Unique with combination of userID + Username + Date 日期是唯一的,结合了用户ID +用户名+日期

but as its more then 100k records there maybe duplicate date records but wither other user ids and names not with 但由于其超过10万条记录,可能有重复的日期记录,但其他用户ID和名称却没有

now i want Output like 现在我想要输出像

userID      name        amount    Date
     1        mark        50      22-10
     2        kane        110     22-12 
     3        mike        60      22-10

if i try group By with id,name,sum(amount),date it returns multiple rows and answer incorrect 如果我尝试使用id,name,sum(amount)进行分组,日期返回多行并回答不正确

i have tried various combination of distict and SUM etc etc but not succeeded any Solution Thanks 我已经尝试了Distict和SUM等的各种组合,但未成功解决任何问题,谢谢

You typically use a GROUP BY to aggregate one or more fields by one or more other fields. 通常,您使用GROUP BY将一个或多个字段与一个或多个其他字段聚合。

SELECT  userID, Name, SUM(amount), MIN(date)
FROM    YourTable
GROUP BY
        userID, Name

From MSDN: Aggregate functions 从MSDN: 聚合功能

Aggregate functions perform a calculation on a set of values and return a single value. 聚合函数对一组值执行计算并返回单个值。 With the exception of COUNT, aggregate functions ignore null values. 除COUNT以外,聚合函数将忽略空值。 Aggregate functions are often used with the GROUP BY clause of the SELECT statement. 聚合函数通常与SELECT语句的GROUP BY子句一起使用。

some typical aggregate functions are 一些典型的聚合函数是

  • SUM
  • MIN 最小
  • AVG AVG
  • ... ...

From MSDN: GROUP BY 从MSDN: GROUP BY

Groups a selected set of rows into a set of summary rows by the values of one or more columns or expressions in SQL Server 2008 R2. 通过SQL Server 2008 R2中一个或多个列或表达式的值将选定的行集合分组为一组摘要行。 One row is returned for each group. 每个组返回一行。 Aggregate functions in the SELECT clause list provide information about each group instead of individual rows. SELECT子句列表中的聚合函数提供有关每个组而不是单个行的信息。

select 
  userId, name, sum(amount) as amount
from
  table
group by
  userId, name

You don't want DISTINCT here, but rather GROUP BY with the aggregate SUM() 您不希望在此处DISTINCT ,而希望使用汇总SUM() GROUP BY

SELECT 
  userID,
  name,
  SUM(amount) AS amount
FROM tbl
GROUP BY userID, name

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

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