简体   繁体   中英

MS Access SQL - Removing Duplicates From Query

MS Access SQL - This is a generic performance-related duplicates question. So, I don't have a specific example query, but I believe I have explained the situation below clearly and simply in 3 statements.

I have a standard/complex SQL query that Selects many columns; some computed, some with asterisk, and some by name - eg (tab1.*, (tab2.co1 & tab2.col2) as computedFld1, tab3.col4, etc).

This query Joins about 10 tables. And the Where clause is based on user specified filters that could be based on any of the fields present in all 10 tables.

Based on these filters, I can sometimes get records with the same tab4.ID value.

Question: What is the best way to eliminate duplicate result rows with the same tab4.ID value. I don't care which rows get eliminated. They will differ in non-important ways.

Or, if important, they will differ in that they will have different tab5.ID values; and I want to keep the result rows with the LARGEST tab5.ID values.

But if the first query performs better than the second, then I really don't care which rows get eliminated. The performance is more important.

I have worked on this most of the morning and I am afraid that the answer to this is above my pay scale. I have tried Group By tab4.ID, but can't use "*" in Select clause; and many other things that I just keep bumping my head against a wall.

Access does not support CTEs but you can do something similar with saved queries.
So first alias the columns that have same names in your query, something like:

SELECT tab4.ID AS tab4_id, tab5.ID AS tab5_id, ........

and then save your query for example as myquery .

Then you can use this saved query like this:

SELECT q1.*
FROM myquery AS q1
WHERE q1.tab5_id = (SELECT MAX(q2.tab5_id) FROM myquery AS q2 WHERE q2.tab4_id = q1.tab4_id)

This will return 1 row for each tab4_id if there are no duplicate tab5_id s for each tab4_id .
If there are duplicates then you must provide additional conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM