访问 SQL 多个 LEFT JOIN 无法工作
Access SQL for multiple LEFT JOIN cant work
表A
Shop ID
Item
Price
Shop A
Item1
101
Shop A
Item2
102
Shop A
Item3
103
Shop A
Item4
104
Shop A
Item5
105
Shop A
Item6
106
Shop A
Item7
107
......
.....
.....
Shop A
Item27
127
Shop B
Item1
201
Shop B
.....
.....
Shop B
Item27
227
Shop C
Item1
301
Shop C
.....
.....
Shop C
Item27
327
假设我有一个像上面那样的 table,我想在其中转换为下面的 table
Shop ID
Item1
Item2
Item3
Item4
.....
Item27
Shop A
101
102
103
104
.....
127
我尝试使用具有多个左连接的查询
SELECT T1.[Shop ID], T1.[Price] AS Item1 .... T27.[Price] AS Item 27
FROM (TableA AS T1
LEFT JOIN TableA AS T2 ON T1.[Shop ID] = T2.[Shop ID])
LEFT JOIN TableA AS T3 ON T1.[Shop ID] = T3.[Shop ID])
...
LEFT JOIN TableA AS T27 ON T1.[Shop ID] = T27.[Shop ID]
WHERE T1.[Item] = 'Item1'
AND T2.[Item] = 'Item2'
...
AND T27.[Item] = 'Item27'
AND T1.[Shop ID] = 'Shop A'
这适用于较少数量的 LEFT JOIN,但当 LEFT JOIN 的数量 > 20 时,访问基本上永远停止,我的实际 table 有点复杂。任何人都可以建议转换方法吗? TIA
一种方法是使用数据透视查询:
SELECT
[Shop ID],
MAX(IIF([Item] = "Item1", Price, NULL)) AS Item1,
MAX(IIF([Item] = "Item2", Price, NULL)) AS Item2,
MAX(IIF([Item] = "Item3", Price, NULL)) AS Item3,
...
MAX(IIF([Item] = "Item27", Price, NULL)) AS Item27
FROM TableA
GROUP BY [Shop ID]
ORDER BY [Shop ID];
您也可以使用 MS Access 查看交叉表选项。
像这样尝试交叉表查询-
TRANSFORM First(t.Price) AS FirstOfPrice
SELECT t.ShopID
FROM TableA as t
GROUP BY t.ShopID
ORDER BY t.Item
PIVOT t.Item;
输入:
输出:
表A
Shop ID | Item | Price |
---|---|---|
Shop A | Item1 | 101 |
Shop A | Item2 | 102 |
Shop A | Item3 | 103 |
Shop A | Item4 | 104 |
Shop A | Item5 | 105 |
Shop A | Item6 | 106 |
Shop A | Item7 | 107 |
...... | ..... | ..... |
Shop A | Item27 | 127 |
Shop B | Item1 | 201 |
Shop B | ..... | ..... |
Shop B | Item27 | 227 |
Shop C | Item1 | 301 |
Shop C | ..... | ..... |
Shop C | Item27 | 327 |
假设我有一个像上面那样的 table,我想在其中转换为下面的 table
Shop ID | Item1 | Item2 | Item3 | Item4 | ..... | Item27 |
---|---|---|---|---|---|---|
Shop A | 101 | 102 | 103 | 104 | ..... | 127 |
我尝试使用具有多个左连接的查询
SELECT T1.[Shop ID], T1.[Price] AS Item1 .... T27.[Price] AS Item 27
FROM (TableA AS T1
LEFT JOIN TableA AS T2 ON T1.[Shop ID] = T2.[Shop ID])
LEFT JOIN TableA AS T3 ON T1.[Shop ID] = T3.[Shop ID])
...
LEFT JOIN TableA AS T27 ON T1.[Shop ID] = T27.[Shop ID]
WHERE T1.[Item] = 'Item1'
AND T2.[Item] = 'Item2'
...
AND T27.[Item] = 'Item27'
AND T1.[Shop ID] = 'Shop A'
这适用于较少数量的 LEFT JOIN,但当 LEFT JOIN 的数量 > 20 时,访问基本上永远停止,我的实际 table 有点复杂。任何人都可以建议转换方法吗? TIA
一种方法是使用数据透视查询:
SELECT
[Shop ID],
MAX(IIF([Item] = "Item1", Price, NULL)) AS Item1,
MAX(IIF([Item] = "Item2", Price, NULL)) AS Item2,
MAX(IIF([Item] = "Item3", Price, NULL)) AS Item3,
...
MAX(IIF([Item] = "Item27", Price, NULL)) AS Item27
FROM TableA
GROUP BY [Shop ID]
ORDER BY [Shop ID];
您也可以使用 MS Access 查看交叉表选项。
像这样尝试交叉表查询-
TRANSFORM First(t.Price) AS FirstOfPrice
SELECT t.ShopID
FROM TableA as t
GROUP BY t.ShopID
ORDER BY t.Item
PIVOT t.Item;
输入:
输出: