简体   繁体   中英

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:

在此处输入图片说明

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!

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

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

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