简体   繁体   中英

SQL Server - DISTINCT on one column

I have a query where I join 3 relations....A, B &. The join is on a unique id. Table B contains rows similar to each other and I want to do a DISTINCT on a FK column in table B (the PK from A).

To make this more clear:

    A              B           C
---------      ---------   ---------
No. (PK)       Id(PK)       Id (PK)
Name           Role         Address
               No.(FK)      No.(FK)

Table B can have multiple instances of people from table A. I want a query which pulls fields from A, B & C joined on the No. field. Table B can have several rows with the same value for the No. column, therefore I want to perform a DISTINCT on the No. column.

How can I do this?

Example Data:

NAME          ROLE       ADDRESS
---------------------------------------
John Smith    Manager    1, The Village
Dawn French   Secretary  2, The City
John Smith    SQL Dev    1, The Village
Terry Tibbs   HR Manager 8, The Road

This is an example of a join on relations A, B & C:

 SELECT A.Name, B.Role, C.Address 
 FROM A, B, C 
 WHERE A.No = B.No AND B.No = C.No

Table B could contain several John Smiths (the same person) who has multiple roles -> therefore I want to do a DISTINCT on the No. that uniquely identifies a person. This is th ePK of Table A (No.).

Sounds like you want to summarize your results using group by on the No, column. The question is what do you want to do with different values in the other columns when the No. value is the same?

One solution might be:

select a.No, a.Name, 
b.MinRole, b.MaxRole, b.RoleCount,
c.Address
from a 
join (
  select b.No, Min(b.Role) as MinRole, Max(b.Role) as MaxRole, 
  Count(distinct b.Role) as RoleCount
  from b group by b.No
) as b on a.No = b.No
join c on a.No = c.No

This assume a.No is unique in a and a and c have a 1 to 1 on No

In you solutions one person may have multiple roles and multiple addresses. "One column DISTINCT" requires subquery trick (as other folk already showed you). But if your query is to show primary (or just one of many) role and primary address for every one person, your query may be much simpler.

SELECT
A.Name,
(SELECT TOP 1 Role FROM B WHERE B.No = A.No) AS PrimaryRole, -- you may add ORDER BY here
(SELECT TOP 1 Address FROM C WHERE C.No = A.No) AS PrimaryAddress, -- add ORDER BY
FROM A
ORDER BY A.Name

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