Kulbuto
Kulbuto

Reputation: 79

Select the last price according to the date using GROUP BY

I'm trying to do a request with a group BY.

Here is an exemple of my table ticket :

id       DtSell       Price       Qt
1        01-01-2017   3.00        1
1        02-01-2017   2.00        3
2        01-01-2017   5.00        5
2        02-01-2017   8.00        2

And my request :

SELECT id, Price, sum(Qt) FROM ticket
GROUP BY id;

but unfortunately, the price returned is not necessarily the right one; I would like to have the last price according to DtSell like that :

id       Price       sum(Qt)
1        2.00        4
2        8.00        7

But i didn't find how to do it. Can you help me ?

Thank you in advance!!

Upvotes: 1

Views: 1053

Answers (5)

Gordon Linoff
Gordon Linoff

Reputation: 1269953

You can do this with a group_concat()/substring_index() trick:

SELECT id, Price, SUM(Qt)
       SUBSTRING_INDEX(GROUP_CONCAT(price ORDER BY dtsell DESC), ',' 1) as last_price
FROM ticket
GROUP BY id;

Two notes:

  • This is subject to internal limits on the length of the intermediate string used for GROUP_CONAT() (a limit that can easily be changed).
  • It changes the type of price to a string.

Upvotes: 2

SqlKindaGuy
SqlKindaGuy

Reputation: 3591

You can do it like this:

declare @t table (id int, dtsell date, price numeric(18,2),qt int)

insert into @t

values

(1        ,'01-01-2017',   3.00     ,  1),
(1        ,'02-01-2017',   2.00     ,  3),
(2        ,'01-01-2017',   5.00     ,  5),
(2        ,'02-01-2017',   8.00     ,  2)

select x.id,price,z.Qt from (
select id,price,dtsell,row_number() over(partition by id order by dtsell desc ) as rn from @t
)x 
inner join (select SUM(qt) as Qt,ID from @t group by id ) z on x.id = z.id
where rn = 1

Upvotes: 0

flyingfox
flyingfox

Reputation: 13506

You might need a sub query,try below:

   SELECT 
    t1.id,
    (SELECT t2.price FROM ticket t2 WHERE t2.id=t1.id 
       ORDER BY t2.DtSell DESC LIMIT 1 ) AS price, 
    SUM(t1.Qt) 
     FROM ticket t1 GROUP BY t1.id;

Upvotes: 3

Kobi
Kobi

Reputation: 2524

You can select all rows from ticket grouped by id ( to sum quantity), then join to the rows which have the max dtsell for each id group( to select the price).
http://sqlfiddle.com/#!9/574cb9/8

SELECT t.id
         , t3.price
         , SUM(t.Qt)
    FROM   ticket t
    JOIN   ( SELECT t1.id
                  , t1.price
             FROM   ticket t1
             JOIN   ( SELECT id
                           , MAX(dtsell) dtsell
                      FROM   ticket
                      GROUP  BY id ) t2
               ON t1.id      = t2.id
              AND t1.dtsell = t2.dtsell ) t3
      ON t3.id = t.id
    GROUP  BY t.id; 

Upvotes: 0

ravi polara
ravi polara

Reputation: 572

Try this query.

SELECT id, Price, sum(Qt) FROM ticket
GROUP BY id,Price

Your Output;

id       Price       sum(Qt)
1        3.00        4
2        8.00        7

Upvotes: 0

Related Questions