Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access SQL for multiple LEFT JOIN cant work

TableA

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

Suppose I have a table like above in which I would like to convert to table below

Shop ID Item1 Item2 Item3 Item4 ….. Item27
Shop A 101 102 103 104 ….. 127

I tried using query with multiple left joins

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'

This work for smaller number of LEFT JOIN but when number of LEFT JOIN > 20, Access essentially stopped forever, my actual table is a bit more complicate. Any one can suggest ways for the conversion? TIA

>Solution :

One approach is to use a pivot query:

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];

You may also look into cross tab options with MS Access.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading