SQL: Need to remove duplicate rows in query

自古美人都是妖i 提交于 2019-12-23 06:58:26

问题


I need help in getting this result either by using SQL query or procedure. My sample table structure is given below.

Required Result :

docid    status
24       Waiver Requested
26       Waiver Requested
27       Rejected

Table A:

docid
----------
24
26
27

Table b:

docid     Status
24     Waiver Requested
26     Rejected
26     Waiver Requested
27     Rejected
27     Rejected

回答1:


Not knowing all of your business rules other than the one you gave, here is a more general solution.

Create another table (or perhaps your data model already has one) with the possible statuses in them:

CREATE TABLE status_rank (
   status   VARCHAR2(100) NOT NULL,
   rank     NUMBER NOT NULL,
   PRIMARY KEY (status_name)
);

This table is used to rank the statuses in order of precedence. In other words, if "Waiver Requested" should be selected over "Rejected" in the case of duplicates, then use a precedence of 1 for waivers and 2 for rejects.

So now the query can make use of this additional ranking table:

SELECT b.docid, r.status
  FROM b,
       status_rank r,
       (SELECT b.id, min(r.rank)
          FROM b, status_rank r
         WHERE b.status = r.status
         GROUP BY id) s
 WHERE b.docid = s.docid
   AND r.rank = s.rank
   AND b.status = r.status;

There are numerous ways to actually do the query, but this should show you the general idea.




回答2:


This is a very good MSDN article "Find and/or Delete Duplicate Rows" http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DuplicateRows Hope this will be useful.



来源:https://stackoverflow.com/questions/8121890/sql-need-to-remove-duplicate-rows-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!