我有两张桌子:
表1
|ID |Total |Name |
|1 |100 |Car |
|2 |200 |House|
|6 |600 |Car |
和
表2
|ID |Total |Type |
|1 |200 |A |
|1 |300 |B |
|3 |100 |A |
|3 |150 |B |
|4 |400 |A |
|5 |500 |B |
|6 |700 |A |
基本上我想创建一个查询,将所有ID连接到一个结果。我知道有2个表,但有一种结果需要加入3个表。
结果应该是:
|ID|Total |Total A|Total B|Name |
|1 |100 |200 |300 |Car | - IDs from all tables
|2 |200 |- |- |House| - ID from table1
|3 |- |100 |150 |- | - IDs from table2
|4 |- |400 |- |- | - ID from table2(type A)
|5 |- |- |500 |- | - ID from table2(type B)
|6 |600 |700 |- |Dog | - ID from table1 and table2(type A)
这是一个简单的例子,table2中可能有重复的行需要group by。还有很长的where子句,因此性能非常低。结果中的所有ID必须是唯一的。单击表单上的按钮时执行此查询。是否可以创建这种查询?也许我应该先创建一些临时表或简化查询?或者我的表数据结构可能错了?
新的其他数据:
表1
|ID |Total |Name |
|1 |100 |Car |
|2 |200 |House|
|6 |600 |Car |
|1 |400 |House|
在Table1中可以是多个相同的ID行。列名也指定了列' Total'标志(消极或积极)。让我们说价值' Car'是消极的和'#House;'正。
所以结果应该是:
|ID|Total |Total A|Total B|
|1 |300 |200 |300
|2 |200 |- |-
|3 |- |100 |150
|4 |- |400 |-
|5 |- |- |500
|6 |-600 |700 |-
因此,我们看到ID = 1总计= 400-100且ID = 6总计= -600,因为列名称'值'。我的问题是如果我选择Table1.Name来查询然后我得到两个相同的ID行(ID = 1):S是否可以创建这样的查询这么简单?
答案 0 :(得分:1)
根据更新的样本表格重现您的预期输出:
SELECT i.ID
, First(T1.Total) AS [Total]
, Sum(IIf(T2.Type='A',T2.Total,Null)) AS [Total A]
, Sum(IIf(T2.Type='B',T2.Total,Null)) AS [Total B]
FROM ((SELECT DISTINCT ID FROM Table1
UNION
SELECT DISTINCT ID FROM Table2) AS i
LEFT JOIN (SELECT ID, Sum(IIf(Table1.Name='House',Table1.Total,-Table1.Total)) AS Total
FROM Table1
GROUP BY ID) AS T1 ON i.ID=T1.ID)
LEFT JOIN Table2 AS T2 ON i.ID=T2.ID
GROUP BY i.ID
答案 1 :(得分:0)
从example (Previous Stack Question)我发现了这个......
TRANSFORM max(t2Total) AS T2Total
SELECT B.ID, B.Total, B.Name
FROM (SELECT T1.ID, T1.Total, T1.Name, T2.Total as T2Total, T2.Type
FROM table1 T1
LEFT JOIN Table2 T2 ON T1.ID = T2.ID
GROUP BY T1.ID, T1.Total, T1.Name
UNION
SELECT T1.ID, T1.Total, T1.Name, T2.Total, T2.Type
FROM table1 T1
RIGHT JOIN Table2 T2 ON T1.ID = T2.ID
GROUP BY T1.ID, T1.Total, T1.Name) B
PIVOT B.Type;
然而,它取决于:“table2中可能存在需要分组的重复行”意味着......如果您真的意味着该行上的每个值都是重复的,那么您需要将上面的table2切换为:
(Select distinct * from table2) T2
假设您不想要重复项。
我假设类型和ID在table2中是唯一的。如果没有,则“Max”可能无法提供所需的结果。