简体   繁体   中英

What is a productive / efficient way to query a table with repeating fields using T-SQL?

I have a tables (simplified) like this:

Lender
   Id (PK)
   AgencyCode1
   AgencyCode2
   AgencyCode3...
   AgencyCode20

Agency
   AgencyCode
   AgencyName

The Lender table is denormalized data coming from a view for reporting. I need one row in my output for each Lender and I need to join the agency codes to an agency table to get the display name for each agency.

The resulting output I am looking for in each row is:

LenderId, AgencyCode1, AgencyName1, ... AgencyCode20, AgencyName20

What is the pattern that strikes the best balance between performance and (developer) productivity to query something like this?

--Edit, Agency Code wasn't a primary key, as I had originally indicated.

Echoing @Martin Smith's comment, unpivot, join, and pivot would probably be the most efficient, performance wise -- and, through working out the intricacies of how to unpivot and pivot, your developers would be more expereienced and thus more productive over time.

Alternatively, if there are 20 and always 20 denormalized columns, you could just write out 20 left outer joins (under the assumption that ever Lender is not related with 20 Agencies). This is ugly code, and would require SQL to process 20 joins... but if the Agency table is small (where I'd call 8 pages/1 extent small), then the overall processing time might be relatively short. Testing would be called for, to determine which performs best.

As regards to developer productivity overall, keep track of how long everything takes (including posting to SO). When it's done, tally everything up, and use it to show how much time was wasted by your developers having to work with poorly designed tables.

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