DJafari
DJafari

Reputation: 13545

request a sql query

I Have a Table For example posts With this structure and Data :

ID | CatID | SubCatID | Title
-----------------------------
1 | 84 | 85 | Test 1
2 | 84 | 86 | Test 2
3 | 84 | 87 | Test 3
4 | 84 | 85 | Test 4
5 | 84 | 85 | Test 5
6 | 84 | 86 | Test 6

I want 1 query that return rows that group by SubCatID and return rows that have a MaxID From each SubCat

It means I want to return this list:

ID | CatID | SubCatID | Title
--------------------------------
5 | 84 | 85 | Test 5
6 | 84 | 86 | Test 6
3 | 84 | 87 | Test 3

Upvotes: 3

Views: 47

Answers (2)

Nicola Cossu
Nicola Cossu

Reputation: 56397

select t1.* from table as t1
inner join (
select max(id) as greater from table group by subcatid) as t2
on t1.id = t2.greater

Upvotes: 1

Joe Stefanelli
Joe Stefanelli

Reputation: 135848

SELECT t.ID, t,CatID, t.SubCatID, t.Title
    FROM YourTable t
        INNER JOIN (SELECT MAX(ID) AS MaxID, CatId, SubCatID
                        FROM YourTable
                        GROUP BY CatId, SubCatID
                   ) q
            ON t.CatId = q.CatId
                AND t.SubCatID = q.SubCatID
                AND t.ID = q.MaxID

Upvotes: 2

Related Questions