简体   繁体   English

如何仅返回一列中的不同结果,同时允许其他列中的重复结果?

[英]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.我使用主键和外键在内部连接三个表(a、b、c)。 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)?这是我所拥有的,有人会解释如何修改此查询以输出在 COLU2 中具有唯一值的记录,同时仍允许周围列(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.我在 SELECT 和 GROUP BY 之后尝试了 DISTINCT,但我无法让它工作。 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:使用聚合:要保留其不同值的所有列都转到GROUP BY子句,并且您可以在另一列上使用聚合函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM