0

this is my first post so pardon me if my question is not in it's appropriate places or tittle

I have a table like this

ID     DATE    Cat  VALUE  
-------------------------    
1   07/07/2018  A   100  
2   07/07/2018  A   200  
3   07/07/2018  B   300  
4   07/07/2018  B   400  
5   07/07/2018  C   500  
6   07/07/2018  C   600  
7   08/07/2018  A   700  
8   08/07/2018  A   800  
9   08/07/2018  B   900  
10  08/07/2018  B   110  
11  08/07/2018  C   120  

I would like to return

distinct category, sum of value, last record of the category

something like this

Cat sumValue    lastrecord
--------------------------
A   1800        800
B   1710        110
C   1220        120

is it possible to do it in a single query

thanks

I am able to find the SUM

SELECT cat, SUM(value) FROM table GROUP BY cat; 

and find the last ID (autonumber key) using MAX

SELECT MAX(ID), cat FROM table GROUP BY cat;

but i just can't get the value for the last record

AlbertSan
  • 61
  • 1
  • 8

3 Answers3

1

This should do it

declare @t table (id int, cat char, value int);
insert into @t values 
(1, 'A', 100), 
(2, 'A', 200),   
(3, 'B', 300),   
(4, 'B', 400),   
(5, 'C', 500),   
(6, 'C', 600),   
(7, 'A', 700),   
(8, 'A', 800),   
(9, 'B', 900),   
(10, 'B', 110),   
(11, 'C', 120);  
select cat, value, sum  
from 
( select *
       , sum(value) over (partition by cat) as sum 
       , ROW_NUMBER() over (partition by cat order by id desc) as rn 
  from @t
) tt 
where tt.rn = 1
paparazzo
  • 44,497
  • 23
  • 105
  • 176
1

I hope you're looking for something like this,

Please replace the table name with your table name.

SELECT A.id, 
       A.cat, 
       A.date, 
       A.total_value, 
       A1.value 
FROM   (SELECT Max(id)    AS id, 
               cat, 
               Max(date)  AS Date, 
               Sum(value) AS Total_Value 
        FROM   tbl_sof 
        GROUP  BY cat) AS A 
       INNER JOIN tbl_sof A1 
               ON A.id = A1.id 
1

SQLFiddle

SELECT
  t.cat,
  SUM(t.value) as sumValue,
  (
    SELECT
      t3.value
    FROM
      `table` t3
    WHERE
      t3.id = MAX(t2.id)
  ) as lastrecord
FROM
  `table` t
  JOIN
    `table` t2 ON t.id = t2.id
GROUP BY
  cat  

EDIT shorter Version:

SELECT
    t.cat,
    SUM(t.value) as sumValue,
    (SELECT value FROM `table` t2 WHERE t2.id = MAX(t.id)) lastValue
FROM
    `table` t
GROUP BY
    t.cat
SirPilan
  • 4,649
  • 2
  • 13
  • 26