如何从连接查询中删除重复值

时间:2014-04-14 14:59:40

标签: sql sql-server-2008

您好我怎么能从此连接语句中删除重复记录。

SELECT  std_info.Reg_no, std_info.std_name, tut_fee.fee_month, class.class_name 
FROM std_info 
  INNER JOIN tut_fee on std_info.Reg_no=tut_fee.Reg_no 
  INNER JOIN promot on std_info.Reg_no=promot.Reg_no 
  INNER JOIN class on class.class_id=promot.class_id
WHERE std_info.Reg_no not in (SELECT Reg_no 
                              FROM tut_fee 
                              WHERE tut_fee.fee_month=3
                                AND tut_fee.fee_year=2014)

给出结果

 Reg_no     std_name    fee_month   class_name

 1. A01      name1         1           2nd
 2. A01      name1         2           2nd
 3. A02      name2         1           3rd
 4. A02      name2         2           3rd

谢谢大家。

2 个答案:

答案 0 :(得分:0)

dublicat来自专栏“tut_fee.fee_month”,

答案 1 :(得分:0)

首先,我在数据库中创建了临时表,名称为Fee_temp,然后插入查询给出的记录。然后使用Row_Number函数进行分区。并删除列出的所有记录多于1。比如下面给出的。

   insert into Fee_temp SELECT   std_info.Reg_no,std_info.std_name,tut_fee.fee_month,class.class_name FROM
std_info Left  JOIN tut_fee on std_info.Reg_no=tut_fee.Reg_no Left JOIN promot on  std_info.Reg_no=promot.Reg_no Left JOIN
class on class.class_id=promot.class_id
WHERE std_info.Reg_no not in (select  Reg_no FROM tut_fee where  tut_fee.fee_month=3   and tut_fee.fee_year=2014)
 SELECT * from Fee_temp
  With A as
 (
 select Fee_temp.Reg_no,Fee_temp.std_name,Fee_temp.fee_month,Fee_temp.class_name,ROW_NUMBER() 
 OVER (Partition by Reg_no ORDER BY Fee_temp.std_name) As Number from Fee_temp
)
DELETE FROM A WHERE Number>1
SELECT * FROM Fee_temp