简体   繁体   中英

Combine multiple rows using SUM that share a same column value but has different other column values

I thought this would be a very simple query but for some reason, I can't seem to get the results I'm looking for. I have a table that has this structure. I just want a single entry for each account while summing the charges. I don't really care which date I keep, just one of them.

Account Charges Charges2    Date
1       100      50       1/1/2015
1       50       0        1/2/2015
2       50       0        2/4/2015
2       70       30       2/19/2015
3       100      0        1/12/2014
4       0        20       4/3/2015
4       40       20       4/9/2015

The result I want is:

Account Charges Charges2    Date
1       150      50       1/1/2015
2       120      30       2/4/2015
3       100      0        1/12/2014
4       40       40       4/3/2015

The result I currently get is:

Account Charges Charges2    Date
1       100      50       1/1/2015
2       70       30       2/19/2015
3       100      0        1/12/2014
4       40       40       4/9/2015

I thought this would be very simple and I tried below. But this doesn't sum them up, it just seems to return the rows where Charges2 is NOT 0.

SELECT Account, SUM(Charges) As TotCharges, SUM(Charges2) AS TotCharges2
FROM TABLE
GROUP BY Account
ORDER BY Account

You can apply the min() aggregate function to the date to limit the number of rows returned to one per account:

SELECT 
  Account, 
  SUM(Charges)  AS TotCharges, 
  SUM(Charges2) AS TotCharges2, 
  MIN(Date) AS Date
FROM TABLE
GROUP BY Account
ORDER BY Account

Sample SQL Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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