获得不同的重复值

时间:2015-11-03 07:03:39

标签: sql duplicates distinct

您好我使用此查询使用来自同一个表中具有不同参数的数据从表中减去值,但我得到了重复值。任何人都可以看到这里有什么问题吗?

SELECT DISTINCT O.BMF_VOTE BMF_VOTE,
       O.BMF_OPERATING_AGENCY BMF_OPERATING_AGENCY,
       O.BGT_ACTUAL_EXPEND - S.BGT_ACTUAL_EXPEND ,
       O.BGT_PREV_ESTIMATE - S.BGT_PREV_ESTIMATE ,
       O.BGT_EST_YEAR1 - S.BGT_EST_YEAR1 ,
       O.BGT_EST_YEAR2 - S.BGT_EST_YEAR2 ,
       O.BGT_EST_YEAR3 - S.BGT_EST_YEAR3 
  FROM BGT_MOF_FROM O, BGT_MOF_FROM S
 WHERE (O.BMF_MAINDIVISION = '100' AND O.BMF_SUBDIVISION = '300')
       AND (S.BMF_SUBDIVISION = '220' AND S.BMF_MAINDIVISION = '100')

2 个答案:

答案 0 :(得分:0)

在我看来,你错过了这两个表的任何连接条款,而不知道它应该看起来像这样的数据:

FROM BGT_MOF_FROM O, BGT_MOF_FROM S
WHERE O.key = S.key

显然用实际的列名替换密钥。如果你试图做一个半笛卡尔的产品(慢和坏),你应该将查询包装成一个子查询,然后在它上面运行一个独特的。

答案 1 :(得分:0)

桌子上没有加入;这可能是骗局的来源。更清楚地说出你想要的是sub选择(别名为O和S),加入BMF_VOTE和BMF_OPERATING_AGENCY:

SELECT 
   O.BMF_VOTE, O.BMF_OPERATING_AGENCY,
   O.BGT_ACTUAL_EXPEND - S.BGT_ACTUAL_EXPEND ,
   O.BGT_PREV_ESTIMATE - S.BGT_PREV_ESTIMATE ,
   O.BGT_EST_YEAR1 - S.BGT_EST_YEAR1 ,
   O.BGT_EST_YEAR2 - S.BGT_EST_YEAR2 ,
   O.BGT_EST_YEAR3 - S.BGT_EST_YEAR3 
FROM 
  (
   SELECT * FROM BGT_MOF_FROM
   WHERE BMF_MAINDIVISION = '100' AND 
         BMF_SUBDIVISION = '300'
   ) O
  JOIN 
  (SELECT * FROM BGT_MOF_FROM
   WHERE BMF_SUBDIVISION = '220' AND 
         BMF_MAINDIVISION = '100' 
   ) S
   on 
   O.BMF_VOTE = S.BMF_VOTE and
   O.BMF_OPERATING_AGENCY =  S.BMF_OPERATING_AGENCY

修复您的代码:

SELECT DISTINCT O.BMF_VOTE BMF_VOTE,
   O.BMF_OPERATING_AGENCY BMF_OPERATING_AGENCY,
   O.BGT_ACTUAL_EXPEND - S.BGT_ACTUAL_EXPEND ,
   O.BGT_PREV_ESTIMATE - S.BGT_PREV_ESTIMATE ,
   O.BGT_EST_YEAR1 - S.BGT_EST_YEAR1 ,
   O.BGT_EST_YEAR2 - S.BGT_EST_YEAR2 ,
   O.BGT_EST_YEAR3 - S.BGT_EST_YEAR3 
FROM BGT_MOF_FROM O, BGT_MOF_FROM S
WHERE 
   (O.BMF_VOTE = S.BMF_VOTE and O.BMF_OPERATING_AGENCY =  S.BMF_OPERATING_AGENCY) 
   AND 
   (O.BMF_MAINDIVISION = '100' AND O.BMF_SUBDIVISION = '300')
   AND 
   (S.BMF_SUBDIVISION = '220' AND S.BMF_MAINDIVISION = '100')