Only the distinct values after a group by in SQL Server 2014

时间:2015-06-15 14:44:58

标签: sql sql-server group-by distinct sql-server-2014

Here is the sample of the data:

 ID     Value   NumPeriod 
 ------------------------     
 1681642    596.8   2 
 1681642    596.8   3 
 1681663    445.4   2
 1681663    445.4   3 
 1681688    461.9   3 
 1681707    282.2   3 
 1681724    407.1   3
 1681743    467     2 
 1681743    467     3 
 1681767    502     3

I want to group by the [ID] and take only the distinct values of [Value] within each group and take the "first" distinct [Value] according to [NumPeriod]. So the result would look something this:

 ID     Value   NumPeriod 
 -------------------------     
 1681642    596.8   2 
 1681663    445.4   2
 1681688    461.9   3 
 1681707    282.2   3 
 1681724    407.1   3
 1681743    467     2 
 1681767    502     3

So I though something like this would work, but no luck:

select 
    ID, distinct(Value), NumPeriod
from 
    MyTable
group by 
    ID, Value, NumPeriod
order by 
    ID, NumPeriod

Any help would be appreciated. Thanks!

2 个答案:

答案 0 :(得分:5)

You can use a ranking function and a CTE:

WITH CTE AS
(
    SELECT ID, Value, NumPeriod,
           RN = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY NumPeriod ASC)
    FROM MyTable
)
SELECT ID, Value, NumPeriod
FROM CTE
WHERE RN = 1
ORDER BY ID, Value

答案 1 :(得分:0)

I think all you have to change is where you call distinct. Try this:

select distinct ID, Value, NumPeriod
from MyTable
group by ID, Value, NumPeriod
order by ID, NumPeriod