[英]How to get the last record using group by
My Query :- 我的查询:
SELECT
p.*,
b.brand_name
FROM
portfolio p,
branding_category b
WHERE
p.category = 'BRANDING'
AND
p.brand_category = b.id
AND
is_active = '1'
GROUP BY
p.brand_category
ORDER BY p.id DESC
LIMIT 10
Suppose portfolio table has :- 假设投资组合表具有:
id category brand_category is_active title
1 test 8 1 abc
2 test 7 1 pqr
3 test 8 1 xyz
4 test 7 1 ijk
And I want to show Output has :- That is, the last record in each group should be returned. 我想显示Output具有:-也就是说,应该返回每个组中的最后一条记录。
id category brand_name is_active title
3 test Catalogs 1 xyz
4 test Posters 1 ijk
Edit :- 编辑:-
branding_category
id brand_name
8 Catalogs
7 Posters
ie, Last row for each group. 即,每个组的最后一行。 Please help me on this. 请帮我。 I know it is there in stackoverflow Retrieving the last record in each group but I am not able to write for two table. 我知道它在stackoverflow中。 检索每个组中的最后一条记录,但是我不能写两个表。
Try this :- 尝试这个 :-
SELECT p.*,b.brand_name
FROM portfolio p
INNER JOIN branding_category b ON p.brand_category = b.id
INNER JOIN (
SELECT MAX(id) MaxMsgIDForThread
FROM portfolio
WHERE is_active = '1'
GROUP BY brand_category
) g ON p.id = g.MaxMsgIDForThread
Order by p.id Desc
LIMIT 10
Try this, 尝试这个,
select x.id,x.category,x.brand_name,x.is_active,x.title from (
select
p.id,p.category,pc.brand_name,p.is_active,p.title,
ROW_NUMBER()over ( ORDER BY p.id) as Rnk
from portfolio p inner join branding_category pc
on p.brand_category=pc.id
) x where Rnk >2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.