Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

Fetch rows based on their values in a group in SQL Server table

id      dept         Person       Rating
-------------------------------------------
1       ece            p1           R1  
2       ece            p2           t1
3       eee            P3           R2             
4       eee            p4           M
5       Civil          P5           R2
6       Civil          P6           t2
7       Civil          P7           t2
8       Mech           p8           R2
9       Mech           P9           Null
10      IT             P10          R2J
11      IT             P11          T2
12      IT             P12          T2

I would like to fetch all the dept rows whose ratings are null in a dept ,or whose ratings are M in a dept, or whose " t" ratings are different to that of "P" in a dept.

Desired output:

3       eee            P3           R2             
4       eee            p4           M
8       Mech           p8           R2
9       Mech           P9           Null
10      IT             P10          R2J
11      IT             P11          T2
12      IT             P12          T2

Note 1: "t" ratings are different to that of "R" in a dept, it means if a person rating in a dept is R2 then other persons in dept ratings is T1. Example dept IT.

Note 2: "t" ratings are same to that of "R" in a dept, it means if a person rating in a dept is R1 then other persons in dept ratings is T1. Example dept ECE.

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(from another question of yours I doubt you are understanding the replies, anyway I hope you at least try)

Select * from myTable t1
where exists (
select * from myTable t2 
where t1.dept = t2.dept AND
  (t2.rating = 'M' or 
   t2.rating is null or 
   right(t1.Rating,1) <> right(t2.Rating,1))
);

DBFiddle Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...