SQL-在合并行时跨表查询匹配数据
我有两张桌子;即 表1:SQL-在合并行时跨表查询匹配数据,sql,excel,vba,Sql,Excel,Vba,我有两张桌子;即 表1: RecordId RecordDescription 1 Red 2 Green 3 Blue 表2: RecordID FieldID FieldValue 1 10 3.1 1 20 2.8 1 30 4.2 2 20 3.8 3 10
RecordId RecordDescription
1 Red
2 Green
3 Blue
表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
我想生成一个组合表,它看起来像:
表3:
这看起来应该很简单,但我一直在兜圈子
感觉我应该能够使用:
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
但我似乎无法正确使用语法,似乎有一种更优雅的方法(我实际上有很多FieldID值…)
任何帮助都将不胜感激。
实际上,我正试图通过excel中的VBA调用来实现这一点,因此一个查询调用将是理想的选择。这称为表透视。一些数据库支持
pivot
子句。您正在使用条件聚合
以下是您可能想要的:
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
如果您不知道
fieldid
值的最大数量,则可能需要研究使用动态sql
这称为表透视。一些数据库支持pivot
子句。您正在使用条件聚合
以下是您可能想要的:
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
如果您不知道
fieldid
值的最大数目,您可能需要研究使用dynamic sql
您的数据库在运行什么?老实说,我不确定。我通过Excel 2010中VBA的ADODB调用访问它。“提供者”是“SQLOLEDB”。我很确定它是Microsoft SQL Server。你的数据库运行在什么地方?老实说,我不确定。我通过Excel 2010中VBA的ADODB调用访问它。“提供者”是“SQLOLEDB”。我很确定这是微软的SQL服务器。是的!这很有魅力。我确实错过了小组,虽然我尝试过给表格添加别名,但我不确定我做得是否正确。非常感谢!!!是 啊这很有魅力。我确实错过了小组,虽然我尝试过给表格添加别名,但我不确定我做得是否正确。非常感谢!!!