Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT last row if USER is found

I have a log table in SQL Server. Table is structured this way:

Unique  ProblemID  ResponsibleID  AssignedToID  ProblemCode

155     155        0282                         4
156     155                       0900
157     155                                     3
158     155                       0147          1
159     159        0111                         2
160     159                       0333          4
161     159        0900                         1

So basically we log all problems and who was responsible/had to deal with the problem. I need a query that would find which problems one person was involved in:

For example:

  1. Person with ID 0900 was involved in both 155 and 159.
  2. Person with ID 0282 was involved in 155 only.
  3. Person with ID 0333 was involved in 159 only.

Also I forgot to mention that I need to filter the last row of ProblemID by the ProblemCode. For example find problemID where person is involved, but there the ProblemCode in the last log line of that problem is 1 (Which means the problem is now closed).

Furthermore, I was working with query:

    select ProblemID, EntryTime, ResponsibleID, ProblemCode, AssignedToID
    from (select ProblemID, EntryTime, ResponsibleID, ProblemCode,  AssignedToID,
    row_number() over(partition by ProblemID order by EntryTime desc) as rn
    from myTable) as T
    where rn = 1 and ResponsibleID = '00282' OR AssignedToID = '00282' 
    and veiksmoid <> 4

However, it ONLY matches the last rows.

like image 649
GEMI Avatar asked Nov 28 '25 22:11

GEMI


1 Answers

This gives you all the problems that a person 0900 dealed with and that have problemCode=1 in their last line. I can't test it so there might be some errors.

SELECT problemID FROM <table> t1
WHERE problemID IN  (
      SELECT problemID FROM <table>
      WHERE (ResponsibleID = 0900 OR AssignedToID = 0900))
AND problemCode = 1
AND unique = (SELECT MAX(unique) FROM <table> WHERE problemID = t1.problemID)
like image 175
phil Avatar answered Dec 01 '25 13:12

phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!