我正在尝试与group BY进行请求。
这是我的票证的一个例子:
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
但是我没有找到方法。 你能帮我吗?
提前谢谢!
答案 0 :(得分:2)
您可能需要子查询,请尝试以下操作:
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;
答案 1 :(得分:1)
您可以使用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
的类型更改为字符串。答案 2 :(得分:0)
尝试此查询。
SELECT id, Price, sum(Qt) FROM ticket
GROUP BY id,Price
您的输出;
id Price sum(Qt)
1 3.00 4
2 8.00 7
答案 3 :(得分:0)
您可以从按ID分组的票证中选择所有行(总计数量),然后加入每个ID组具有最大卖点的行(以选择价格)。
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;
答案 4 :(得分:0)
您可以这样做:
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