当第二个表来自SQL查询时,连接SQL表

时间:2017-05-26 10:54:54

标签: sql join access-vba

我是编程新手,我无法正确地获取SQL语法以加入以下两个表(点表示其他不相关的列)。

T1:Code1,name,... T2:Code2,value,ID1,ID2,......

SELECT code1, name FROM T1

- >生成表1

SELECT Code2, SUM(value) FROM T2 WHERE ID1 = X and ID2 = X GROUP BY Code 2

- >制作表2

我现在想要连接表1和2 ON TRIM(T1.code1) = TRIM(T2.code2)(修剪删除导致不匹配的空格)。

T1包含没有值的条目,我想要显示。所以我先尝试使用T1并使用LEFT OUTER JOIN,但我似乎无法做到正确。有什么建议吗?

提前感谢你, 乔治

EDIT1 - 由于我还没有说明该平台,因此SQL字符串将在MS Access中用于使用rowsource命令填充列表框。

EDIT2 - 样本数据和期望的结果

T1:

Code1   | Name
---------------
1       |  a
2       |  b
3       |  c
4       |  d

T2

Code 2 | Value
---------------
1      |   10
1      |   20
1      |   25
2      |   5
2      |   10
4      |   30
4      |   60

期望的结果:

Code  | Name  |  Total
1     |   a   |   55
2     |   b   |   15
3     |   c   |   0 (or NULL)
4     |   d   |   90

希望这有帮助

2 个答案:

答案 0 :(得分:1)

只需用括号括起您的查询:

select trim(q1.code1) as code, q1.name, q2.total
from (SELECT code1, name FROM T1 ) q1
left join
(
  SELECT Code2, SUM(value) as total FROM T2 
  WHERE ID1 = X and ID2 = X
  GROUP BY Code2
) q2 on trim(q2.code2) = trim(q1.code1);

如果您在table1上没有任何WHERE子句,则可以将其减少为:

select trim(t1.code1) as code, t1.name, q2.total
from t1
left join
(
  SELECT Code2, SUM(value) as total FROM T2 
  WHERE ID1 = X and ID2 = X
  GROUP BY Code2
) q2 on trim(q2.code2) = trim(t1.code1);

答案 1 :(得分:0)

我猜您的查询可能是:

SELECT T1.code1, T1.name, T3.tot
FROM T1 LEFT OUTER JOIN
(SELECT Code2, SUM([value]) AS tot
    FROM T2 WHERE ID1 = X and ID2 = X
    GROUP BY Code2) T3
ON TRIM(T1.code1) = TRIM(T3.code2)