0

I have a select query as part of an on_click event within a form.

varSQL2 = "SELECT DISTINCT(*), count(*) AS Count1" & _
          " FROM Inventory WHERE Part_ID='" & rs!Part_ID & "';"

I am wondering what the correct syntax for this query would be. I would like all records that match the ID and then a count of how many there are. Is this syntax correct?

It may be found that this is the correct syntax, however, I am neither getting an error nor response.

Can anyone suggest a better alternative. I have seen cases where a subquery has been used, but I don't really understand the difference between that and what I have used.

1
  • 1
    No. You cannot mix columns and group functions without a GROUP BY clause. You have to select your rows in a query, and perform the count in another query. Commented Oct 12, 2015 at 13:04

2 Answers 2

2

As Sergio wrote, you need a subquery like this:

SELECT Count(*) AS Count1
FROM (
    SELECT DISTINCT * 
    FROM Inventory 
    WHERE Part_ID = [ rs!Part_ID ] 
)
Sign up to request clarification or add additional context in comments.

Comments

1

For getting a count on how many recordsets have a specific Part_ID use:

varSQL2 = "SELECT count(*) AS Count1" & _
          " FROM Inventory WHERE Part_ID='" & rs!Part_ID & "';"

Now to your used DISTINCT(*) : I do not know what the purpose was, because of missing explanation, but it would compress exactly equal recordsets. If you follow the idea of a relational database design (which Access is thought for), you will never have two exact table-entries in one table.

So, if you wanted to achieve anything with this distinct, please explain it in your question, that we can help you.

4 Comments

The distinct removes duplicates. I created a query in the query designer and I was getting duplicate results (not sure why) so I included the distinct to prevent issues.
Okay then use @andre451 's answer. But I recommend you anyway to check your database-design, because having duplicate recordsets in one table is a little bit strange except you wanted that explicitly.
asdev has a very valid point here. If SELECT DISTINCT * FROM Inventory gives a different number of records than SELECT * FROM Inventory, then your table has no primary key which is bad. --- SELECT DISTINCT is typically used when selecting only a single or a subset of fields from a table. @LiamH
I may not have been very clear as the syntax is different. my fault. however, I have asked this as a separate question here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.