简体   繁体   English

SQL - 在组合行时跨表查询匹配数据

[英]SQL - query matching data across tables while combining rows

I have two tables; 我有两张桌子; ie

Table1: 表格1:

RecordId    RecordDescription
1           Red
2           Green
3           Blue

Table2: 表2:

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: 我想生成一个组合表,看起来像: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...) 但我似乎无法使我的语法正确,似乎可能有一个更优雅的方式(我实际上有相当多的FieldID值......)

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. 我实际上是尝试在excel中的VBA调用中执行此操作,因此单个查询调用将是理想的。

This is called table pivoting. 这称为表旋转。 Some databases support the pivot clause. 某些数据库支持pivot子句。 You are using conditional aggregation . 您正在使用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 . 如果您不知道fieldid值的最大数量,则可能需要研究使用dynamic sql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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