简体   繁体   中英

How to return only distinct results within one column, while allowing duplicates in other columns?

I'm having a hard time figuring out how to output what I want. I want to remove duplicates from one column only, while allowing duplicates in other columns. I'm inner joining three tables (a,b,c) using primary and foreign keys. Here's what I have, will someone explain how to modify this query to output records having a unique value in COLU2, while still allowing duplicates in the surrounding columns (COLU1, COLU3)?

QUERY:

DECLARE @Email NVARCHAR(50)
SET @Email = 'user@email.com'
SELECT a.nameF, a.nameL, a.email b.TestName, c.testScore FROM a
INNER JOIN b
ON a.a_primaryKey=b.a_foreignKey
INNER JOIN c
ON b.b_primaryKey=c.b_foreignKey
WHERE a.email = '%' + @Email + '%'

CURRENT OUTPUT:

    COLU1      | COLU2 | COLU3
------------------------------
user@email.com | test1 | 80
user@email.com | test1 | 90
user@email.com | test2 | 83
user@email.com | test3 | 89

WISHLIST OUTPUT:

    COLU1      | COLU2 | COLU3
------------------------------
user@email.com | test1 | 80
user@email.com | test2 | 83
user@email.com | test3 | 89

I've tried DISTINCT after SELECT along with GROUP BY, but I couldn't get it to work. Thanks all.

I want to remove duplicates from one column only, while allowing duplicates in other columns.

Use aggregation: all columns whose distinct values you want to retain go to the GROUP BY clause, and you can use an aggregate function on the other column:

SELECT a.nameF, a.nameL, a.email b.TestName, MIN(c.testScore) score
FROM a
INNER JOIN b ON a.a_primaryKey=b.a_foreignKey
INNER JOIN c ON b.b_primaryKey=c.b_foreignKey
WHERE a.email = '%' + @Email + '%'
GROUP BY a.nameF, a.nameL, a.email b.TestName

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