Hi,
I have a query based on a single table of items in invoices (approx. 30,000 records; named X) with subqueries performing distinct counts and summation.
The table looks something like this (one record = one item):
Document_ID |
Item_No |
Item_Class |
Amount |
1 |
1 |
X |
10 |
1 |
2 |
X |
20 |
1 |
3 |
Y |
25 |
2 |
1 |
Y |
16 |
2 |
2 |
Y |
22 |
2 |
3 |
Z |
34 |
2 |
4 |
X |
40 |
The code (see below) is a reworked version of what I found on a blog.
Code:
SELECT Main.Document_ID,
(SELECT Count(Tmp1.Class) FROM (SELECT DISTINCT Document_ID, Class FROM X GROUP BY Document_ID, Class ORDER BY Document_ID )
AS Tmp1
WHERE Main.Document_ID = Tmp1.Document_ID
GROUP BY Tmp1.Document_ID ORDER BY Tmp1.Document_ID) AS Count_of_Class,
Count(Main.Item_No) AS Count_of_items,
Sum(Main.Amount) AS Amnt
INTO TableXYZ
FROM X AS Main
GROUP BY Main.Document_ID
ORDER BY Main.Document_ID;
My questions:
1. The query takes a really long time to execute. How do I speed it up?
I have seen people suggesting INNER JOINs into queries to speed them up, however, I am not really sure how I would do that or in what way this would work in this case. Maybe someone knows how I would go about doing this or even has a completely different suggestion?
2. The query won't run unless I assign the original table an alias ("Main" in the code above). Can someone explain why this is so essential?
I'd really appreciate any help since I'm totaly new to Access and SQL. I've been progressing at a snail's pace with this and seem to be finally stuck after days of scrutinizing forums all over the place.
Sorry if this has been discussed before or if I left out any essential context...
Regards,
Peter
EDIT: One more question: I have been able to run the above query without the WHERE clause and am not entirely sure how that is possible. I have also tried substituting the WHERE clause FOR
Code:
INNER JOIN X Main ON Main.Document_ID = Tmp1.Document_ID
but got an error saying "At most one record can be returned by this subquery."
Why does this happen?
Thanks in advance, again, for ANY help!