Home > Enterprise >  limit results based upon 1 column
limit results based upon 1 column

Time:05-12

I'm a SQL newbie, any help is greatly appreciated! The id is the ID of a person that is in a program, and STI is the step ID that correlates to the ID of the step they are currently on or have completed. What I'm having a hard time figuring out is how to limit the results to only show unique Person ID's. I can't get DISTINCT to work at all. Here is the query:

SELECT
    s.[PersonAliasId] AS [id]
  , s.[StepTypeId] AS [sti]
FROM
    [Step] s
ORDER BY s.[PersonAliasId]

The results from the above query are:

id      sti
11126   19
47331   19
66693   7
68110   19
74838   7
89867   1
89867   2
110105  19
122059  19
122059  21
130273  7
139876  19
150180  19
161929  7
165926  19
169329  19
171922  19

There are multiple steps that we are tracking for each person. When they have completed one step and then moved to another, they show in this query twice. For example, person 122059 has completed step id 19 and are currently on step id 21. I don't really care about the multiple step numbers showing, I really only need the person ID to return once. Can anyone help me figure out what I'm doing wrong?

CodePudding user response:

From my understanding of your question. You only care about unique id. So you could try to use the MAX() function to get the max step for each id.

select 
distinct(s.PersonAliasId) AS id,
max(s.StepTypeId) AS sti
FROM Step s
GROUP BY s.PersonAliasId
ORDER BY s.PersonAliasId

db fiddle link

Let me know if I misunderstood anything

  •  Tags:  
  • tsql
  • Related