简体   繁体   中英

SQL - query matching data across tables while combining rows

I have two tables; ie

Table1:

RecordId    RecordDescription
1           Red
2           Green
3           Blue

Table2:

RecordID    FieldID   FieldValue
1           10        3.1
1           20        2.8
1           30        4.2
2           20        3.8
3           10        6.6
3           30        5.5

I would like to generate a combined table that looks something like: Table3:

RecordID   Field10Value   Field20Value   Field30Value
1               3.1            2.8          4.2
2                              3.8 
3               6.6                         5.5

This seems like it should be pretty straight forward, but I keep driving myself in circles.

It feels like I should be able to use:

SELECT * FROM (
  SELECT RecordID, Field10Value, Field20Value, Field30Value FROM (
  SELECT MAX(CASE WHEN FieldID=10 THEN FieldValue ELSE NULL END) as Field10Value,
  SELECT MAX(CASE WHEN FieldID=20 THEN FieldValue ELSE NULL END) as Field20Value,
  SELECT MAX(CASE WHEN FieldID=30 THEN FieldValue ELSE NULL END) as Field30Value 
  FROM Table2)) JOIN Table1 on RecordID

But I can't seem to get my syntax right and it seems like there may be a much more elegant way (I actually have quite a few FieldID values...)

Any help would be greatly appreciated. I'm actually trying to do this from a VBA call in excel, so a single query call would be ideal.

This is called table pivoting. Some databases support the pivot clause. You are using conditional aggregation .

Here's what you're probably after:

select t1.recordid, t1.recorddescription, 
       max(case when t2.fieldid = 10 then t2.fieldvalue end) as field10value,
       max(case when t2.fieldid = 20 then t2.fieldvalue end) as field20value,
       max(case when t2.fieldid = 30 then t2.fieldvalue end) as field30value
from table1 t1 
       join table2 t2 on t1.recordid = t2.recordid
group by t1.recordid, t1.recorddescription

If you don't know the maximum number of fieldid values, you will probably need to look into using dynamic sql .

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