

SQL Select a row for each category type
source link: https://www.codesd.com/item/sql-select-a-row-for-each-category-type.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

SQL Select a row for each category type
I've the data in my table in following format.
id | person_id| category | value| updated_date
-----------------------------
1 | p1 |race | r1 | 2015-02-26
2 | p1 |race | r2 | 2015-02-26
3 | p2 |race | r3 | 2015-02-27
4 | p2 | race | r1 | 2015-02-28
5 | p1 | lang | l1 | 2015-02-26
Now, I'm filtering based on the person's id. I need following in the result set.
- I need a record for each category that exists for this person.
- If there is more than one record for a category, list the once that is updated last.
- If the updated dates are same, get the first one in the list.
For p1,
1 | p1 |race | r1 | 2015-02-26
5 | p1 | lang | l1 | 2015-02-26
It's something like this. because id is not a group by field because it changes on every row you select the min(id) for the group by personid,category, value.
select min(id), personid, category, value, max(updated_date)
group by personid, category, value
having Max(updated_date)
/* min(id) is just to return the value of id
for the row having max(update_date)
having max(update_date) get's the highest date*/
Recommend
-
28
The ISO/IEC 9075:2016 standard, or SQL:2016 in short, introduces support for a profound concept called Row Pattern Recognition (RPR) in SQL. I posted a
-
5
Add Multiple Post Type to Category Archive Page We use cookies for commenting and analytics. For more details, please visit our privacy page.
-
12
An Understanding of Each Type – CryptoMode Search It has been 12 years since Bitcoin was first launched, and since then,
-
10
SQL Insert a row or rows of data? advertisements I am working on a console application to insert data to a MS SQL Server 2005 database. I have a li...
-
10
SQL: Select the sum of each individual value of a column advertisements There is a column that can have several...
-
10
Multiply each row of a matrix with its transpose advertisements The formula I have to translate to Octave/Matla...
-
7
[CSS] Select First Row of Table April 10, 2017 See the demo below. The first r...
-
10
During CIF of Customer, field BU_TYPE ( BP category) is populated incorrectly Skip to Content...
-
3
Row Level Security in Hyperlambda and SQL Row level security i...
-
9
Do I Write Separate Pillar Posts For Each Category? Not sure whether you need to do pillar pages? Expert Tony Wright gives his advice on content structure i...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK