简体   繁体   中英

SQL Increment based on column count

So I have a table (Org_Contacts) that will link a contacts table to an organization.

The table is currently setup like this:

Organization ID (int)
Contact ID (int)
Priority (int)

There may be multiple contacts to an org and I would like to insert the contacts in and based how many contacts are assigned to an org I would like to increment the priority for that contact.

For instance, I have two organizations, ABC(ID:90) and XYZ(ID:91) .

I have 5 contacts for those two organizations. John (ID:10), Jane (ID:11), Steve (ID:12), Bob (ID:13), Jennifer (ID:14)

When I add John to the ABC as a Contact I want the priority to start at 1

Org_Contacts
------------
90|10|1

Next I'll add Jane to the same org as a contact causing her priority to be 2

Org_Contacts
------------
90|10|1
90|11|2

Following that Steve will be added, but he will be a contact for XYZ

Org_Contacts
------------
90|10|1
90|11|2
91|12|1

Bob will be next and will be added to ABC

Org_Contacts
------------
90|10|1
90|11|2
91|12|1
90|13|3

and last is Jennifer to XYZ

Org_Contacts
------------
90|10|1
90|11|2
91|12|1
90|13|3
91|14|2

I am trying to accomplish all of this in an insert statement. I'm thinking maybe a subquery that uses a count, but I'm not sure as to the best approach.

Instead of maintaining the priority within the table it might be easier to calculate it on the fly using ROW_NUMBER (you didn't specify your DBMS, but most support it):

select
   Organization,
   Contact,
   ROW_NUMBER()
   OVER (PARTITION BY Organization
         ORDER BY Contact) AS Priority
from tab

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