简体   繁体   中英

Oracle: how to group by 1st value in row?

Table has 3 columns in a table: ITEM, SUB_ITEM, DATE_CREATED.

ITEM - item id (string)
SUB_ITEM - item id (int)
DATE_CREATE - date the SUB_ITEM was created (date)

Scenario:

  1. There are 3 Different item's (AAA1, AAB2, ABB3)
  2. All 3 of these item's have multiple sub-items.
  3. Each item has a sub-item that is the same for each of them (eg. All 3 of the item's have a SUB_ITEM = 101010)

I am trying to do something like:

select * 
from table 
group by ITEM, SUB_ITEM, DATE_CREATED

How do you make it display only 1 row? I don't care if it chooses AAA1 or AAB2 or ABB3, I just want it to pick 1 and remove the rest so it will show 1 row per SUB_ITEM, but still displays at least one of the parent items.

Edit:

Thank you to mathguy for answering the above question.

Question 2: Is it possible to group by the 1st 2 letters of the item in addition to the sub_item? So instead of returning 1 row, return 2 rows: AAA1 and AAB2 will cascade in to 1 row, and ABB3 will be the 2nd row because 'AA' and 'AB' are different.

Edit 2: See Main Answer comments for answer to question 2

One way is to group by sub_item , and take the max or min over another column (let's say max over date_created ) and whatever is in the remaining column IN THE SAME ROW.

select min(item) keep (dense_rank last order by date_created) as item, 
       sub_item, max(date_created) as date_created
from   table_name
group by sub_item
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM