使用group by根据日期选择最后一个价格

6yjfywim  于 2021-06-24  发布在  Mysql
关注(0)|答案(5)|浏览(394)

我正试着和一组人做一个请求。
这是我的餐桌票的一个例子:

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

我的要求是:

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

但不幸的是,返回的价格不一定是正确的;我想按dtsell的最后价格:

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

但我不知道怎么做。你能帮助我吗?
提前谢谢!!

u5rb5r59

u5rb5r591#

尝试此查询。

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

你的产出;

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

cdmah0mi2#

你可以用一个 group_concat() / substring_index() 技巧:

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

两个注意事项:
这取决于所用中间管柱长度的内部限制 GROUP_CONAT() (很容易改变的限制)。
它改变了 price 一根绳子。

baubqpgj

baubqpgj3#

你可以这样做:

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
0ejtzxu1

0ejtzxu14#

您可能需要子查询,请尝试以下操作:

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;
s5a0g9ez

s5a0g9ez5#

您可以从按id分组的ticket中选择所有行(对数量求和),然后连接到每个id组具有最大dtsell的行(选择价格)。
http://sqlfiddle.com/#!9/574断路器9/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;

相关问题