Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using distinct and sum in sql server 2008

I'm trying to get the SUM(Values) for each Acct, but my issue is trying to get at least one entire row for a DISTINCT Acct with the SUM(Values).

I have some sample data for example:

Acct         Values    Name       Street     
123456789    100.20    John       66 Main Street
123456789    200.80    John       22 Main Avenue
222222222    50.25     Jane       1 Blvd
333333333    25.00     Joe        55 Test Ave
333333333    50.00     Joe        8 Douglas Road
555555555    75.00     Tim        12 Clark Ave
666666666    500.00    Tim        12 Clark Street
666666666    500.00    Tim        3 Main Rd.

My query consisted of:

SELECT DISTINCT Acct, SUM(Value) AS [TOTAL]
FROM TABLE_NAME
GROUP BY Acct

The above query gets me close to what I need, but I need the entire row.

Example below of what I am looking for:

Acct         Total      Name       Addr1     
123456789    301.00     John       66 Main Street 
222222222    50.25      Jane       1 Blvd
333333333    75.00      Joe        55 Test Ave
555555555    75.00      Tim        12 Clark Ave
666666666    1000.00    Tim        12 Clark Street

Thanks.

like image 213
dolm77 Avatar asked Dec 21 '22 05:12

dolm77


1 Answers

If it does not matter what address you return, then you can apply and aggregate to the other columns:

SELECT Acct, 
  SUM(Value) AS [TOTAL], 
  max(name) name, 
  max(Street) addr1
FROM TABLE_NAME
GROUP BY Acct;

See SQL Fiddle with Demo

like image 155
Taryn Avatar answered Jan 11 '23 01:01

Taryn