开发者

how to use distinct in ms access

开发者 https://www.devze.com 2023-02-28 22:50 出处:网络
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

I have two tables. Task and Categories.

how to use distinct in ms access

how to use distinct in ms access

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;

how to use distinct in ms access

Now as multiple cont开发者_如何学Cacts 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?


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号