user262503
user262503

Reputation: 101

How to group and select the latest data record in SQL Server?

I am using SQL Server 2012

The result of my query is like this:

enter image description here

How do I get only record with max(tnxdate) and sum(total)?

Like this:

total    actbucket  tnxbucket
--------------------------------
4        18+   7-12 m

I tried this:

select 
    sum(id), tnxbucket, actbucket 
from
    (select 
        *,
        rn = row_number()over(partition by id order by tnxdate desc) from t
    ) x
where 
   x.rn = 1 
group by 
   tnxbucket, actbucket 

but it gives me like this

total  actbucket  tnxbucket
------------------------------
3    18+  18+
1    18+ 7-12

I want tnxbucket, actbucket that is with max tnxdate

Thanks!

Upvotes: 1

Views: 94

Answers (2)

t-clausen.dk
t-clausen.dk

Reputation: 44346

Try this:

;WITH cte as
(
  SELECT 
    max(tnxdate) over (partition by id) mx, 
    sum(total) over (partition by id) total,
    actbucket, 
    tnxbucket
  FROM t
)
SELECT TOP 1 
  total, 
  actbucket, 
  tnxbucket 
FROM cte
ORDER BY 
  mx desc,
  tnxbucket desc

Upvotes: 1

niyou
niyou

Reputation: 873

Try this one

SELECT t1.total, t1.tnxdate, t2.actbucket, t2.tnxbucket
FROM (SELECT id, SUM(total) as total, MAX(tnxdate) as tnxdate
      FROM table
      GROUP BY id) t1 
        LEFT JOIN table t2 ON t1.id=t2.id AND t1.tnxdate  = t2.tnxdate

Upvotes: 1

Related Questions