how to use distinct in ms access

*爱你&永不变心* 提交于 2019-11-28 03:41:59

问题


I have two tables. Task and Categories.

TaskID is not a primary key as there are duplicate values.When there are multiple contacts are selected for a specific task,taskid and other details will be duplicated.I wrote the query:

SELECT Priority, Subject, Status, DueDate, Completed, Category
FROM Task, Categories
WHERE Categories.CategoryID=Task.CategoryID;

Now as multiple contacts are selected for that task,for the taskid=T4, there are two records(highlighted with gray). I have tried using distinct in ms access 2003 but its not working. I want to display distinct records. (Here there's no requirement to show taskid) If I write :

select priority, distinct(subject), .......

and remaining same as mentioned in above query then its giving me an error. I have tried distinctrow also.But didnt get success. How to get distinct values in ms access?


回答1:


Okay.Its working this way.

SELECT DISTINCT Task.Priority, Task.Subject, Task.Status, Task.DueDate, 
Task.Completed, Categories.Category
FROM Task, Categories
WHERE (((Categories.CategoryID)=[Task].[CategoryID]));



回答2:


I don't like using SELECT DISTINCT, I have found that it makes my code take longer to compile. The other way I do it is by using GROUP BY.

    SELECT Priority, Subject, Status, DueDate, Completed, Category
    FROM Task, Categories
    WHERE Categories.CategoryID=Task.CategoryID
    GROUP BY Subject;

I do not have VBA up at the moment but this should work as well.




回答3:


Using SELECT DISTINCT will work for you, but a better solution here would be to change your database design.

Duplicate records may lead to inconsistent data. For example, imagine having two different status in different records with the same TaskID. Which one would be right?

A better design would include something like a Task table, a Contact table and an Assignment table, as follows (the fields in brackets are the PK):

Tasks: [TaskID], TaskPriority, Subject, Status, DueDate, Completed, StartDate, Owner, CategoryID, ContactID, ...

Contact: [ID], Name, Surname, Address, PhoneNumber, ...

Assignment: [TaskID, ContactID]

Then, you can retrieve the Tasks with a simple SELECT from the Tasks tables. And whenever you need to know the contacts assigned to a Tasks, you would do so using the JOIN clause, like this

SELECT T.*, C.*
FROM TaskID as T 
  INNER JOIN Assignment as A
    ON T.TaskID = A.TaskID
  INNER JOIN Contac as C
    ON A.ContactID = C.ID

Or similar. You can filter, sort or group the results using all of SQL's query power.



来源:https://stackoverflow.com/questions/5788586/how-to-use-distinct-in-ms-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!