简体   繁体   中英

SQL MS-Access Select Distinct for multiple columns

sorry for asking on this topic again, but I havent been able to derive a solution to my problem from existing answers.

I have one Table (" Data ") from which I need to pull three columns ( " PID ", " Manager ", " Customer " ) and only the " PID " has to be distinct. I dont care which records are pulled for the other columns (" Manger " / " Customer " ) it could be the first entry or whatever.

SELECT Distinct PID, Manager, Customer
FROM Data;

Will give me all the rows where PID,Manager and Customer are distinct, so if there is two entrys with the same PID but with a different Manager, I will get two records instead of one.

Thank you very much.

You can do this Hope you will find this helpful

SELECT PID, max(Manager), max(Customer)
FROM Data
group by PID

Or

   SELECT PID, min(Manager), min(Customer)
FROM Data
group by PID

EDIT

I will give you an example to explain you the Max & Min Func

Here is the Sample Table

CREATE TABLE data(
    PID int ,
    Manager varchar(20) ,
    Customer varchar(20) 
) ;


insert into data
values
(1,'a','b'),
(1,'c','d'),
(3,'1','e'),
(3,'5','e'),
(3,'3','e')

Now,

These are the Three Queries that will return respective outputs,,

select * from data;


SELECT PID, max(Manager), max(Customer)
FROM Data
group by PID;


  SELECT PID, min(Manager), min(Customer)
FROM Data
group by PID

Output for the above queries is

在此处输入图片说明

Explanation : MAX :

MAX is returning C & 5 for Manager Coz, C is greater then A & likewise 5 is greater then 1 & 3

Min fuction is totally opposite of MAX function & is self explenatory.

I have also created on demo Please click to see the demo on Fiddle

Click Here To See The Demo

SELECT "PID", max("Manager"), max("Customer")
FROM "Data"
GROUP BY "PID";

This query returns unique "PID"s and max values of "Manager" and "Customer" for each "PID".

DISTINCT is applied for all the columns from the select list. So you need to use GROUP BY + an aggregate function (returns one value for several rows).

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