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
425 views
in Technique[技术] by (71.8m points)

sql - Filter duplicate rows based on a field

I have several records (bills) that are basically duplicates of each other, except for one field, which represents the language that bill is in.

For example:

ID,BillID,Account,Name,Amount,Lang
1,0001,abcd,John Smith,10.99,ENG
2,0002,qwer,Jane Doe,9.99,ENG
3,0001,abcd,John Smith,10.99,SPA
4,0003,abcd,John Smith,4.99,CHI

All fields are strings, except ID, which is an autonumber.

In my SQL select, I have

SELECT * 
FROM Bills 
WHERE Account='abcd'

and it returns 3 rows in total, but 2 rows for the same bill. I need to return unique bills for a specific account. So in the scenario above, I want to retrieve 2 bills with billID 0003 and either SPA or ENG version of 0001, but not both.

What would by query be?

Thank you

EDIT: I cannot rely on a specific language always being there. For example, I cannot say SELECT * FROM Bills WHERE Account='abcd' AND Lang='ENG' because sometimes a bill may be only in one language, which is not ENG, and sometimes may be in several languages in any combination.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Probably the easiest way would be to use ROW_NUMBER and PARTITION BY

SELECT * FROM (
   SELECT b.*,
   ROW_NUMBER() OVER (PARTITION BY BillID ORDER BY Lang) as num
   FROM Bills b
   WHERE Account = 'abcd'
) tbl
WHERE num = 1

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

...