How do i merge two or more rows based on their foreign key?

前端 未结 3 690
北恋
北恋 2020-12-12 04:02

I have three tables which are:

A(a1, a2, a3)

//This tbl (Table) can have multiple instances of a1, but cause of its dependence on b1, 
//we have a unique re         


        
3条回答
  •  离开以前
    2020-12-12 04:59

    OK, let's take a stab and see if this gets us anywhere.

    Table A: GenericTbl(Id, Name, ...)

    Table B: GenericDetails(Id, GenericId, ...)

    Table C: Strengths(Id, GenericDetailsId, Strength, Unit, DosageForm, ...)

    If when you say merge you're looking for an output set which puts the results together for the strengths of a single generic you could do something along the lines of

    SELECT
     g.Id,
     g.Name,
     gd.Id,
     s.Strength,
     s.Unit,
     s.OtherFields /*fill in the blanks*/
    FROM
     GenericTbl g
      INNER JOIN GenericDetails gd
       on g.Id=gd.GenericId
      INNER JOIN Strengths s
       ON gd.Id=s.GenericDetailsId
    ORDER BY
     g.Id, gd.Id, s.Id
    

    and that'd give you a single results set listing all the different strengths for each of the generics, grouped their types, with each result on one row.

    If what you want is a single row per type with columns to tell you the options available, it should be doable with cursors and temporary tables, or pivots I think from memory.

    If what you're actually looking for is for the records to be merged on insert into the database so you only have a single underlying record which contains all the data then you could do it through triggers, but I can't quite see why you'd want to because you'd end up with a 1:1 mapping for B and C and might as well just have them as a single table.

提交回复
热议问题