在SQL查询中获取重复项

时间:2018-09-12 15:22:33

标签: sql oracle

尝试使用以下查询创建仪表板-

select a.distinct_id, 
       trunc(a.dte) Transaction_Date, 
       a.dte, 
       a.activity, 
       a.part, 
       a.loading, 
       a.user_name, 
       a.device, 
       a.fromloc, 
       a.toloc, 
       a.to_area, 
       b.NAME||' '||b.Surname Name, 
       a.qty, 
       DECODE(d.workarea, 'Tables','Wood','Metal')Material
from table a,  table b, table c, table d
where (a.toloc = d.storage 
  and a.part = c.part and c.region = 'Country1' 
  and a.dte > trunc(sysdate) - '9' 
  and a.region = 'Country1' 
  and a.activity = 'IDENTIFY' 
  and a.user_name = b.user_name 
  and d.maxarea <> 0 )

当我从where语句中删除最后一个约束(即d.maxarea <> 0)时,输出不会显示重复,但是当我再次在查询中添加该重复时,它会显示具有相同distinct_id的重复记录。

2 个答案:

答案 0 :(得分:3)

您的查询应该这样写:

select a.distinct_id, trunc(a.dte) as Transaction_Date, a.dte, a.activity, a.part, a.loading, a.user_name, a.device, a.fromloc, a.toloc, a.to_area,
       (b.NAME||' '||b.Surname Name), a.qty,
       (case when d.workarea = 'Tables' then 'Wood' else 'Metal' end) as Material   
from a join
     b
     on a.user_name = b.user_name join
     c
     on a.part = c.part join
     d
     on a.toloc = d.storage
where c.region = 'Country1' and
      a.dte > trunc(sysdate) - interval '9' day and
      a.region = 'Country1' and
      a.activity = 'IDENTIFY' and
      d.maxarea <> 0;

我不确定您的实际问题是什么,但是您应该学习编写查询的正确方法:

  • 从不FROM子句中使用逗号。 始终使用正确的,明确的,标准 join语法。
  • decode()是特定于数据库的。标准逻辑为case

答案 1 :(得分:0)

如果要使用不同的行,则需要在代码中添加DISTINCT 就像

  SELECT DISTINCT a.distinct_id, trunc(a.dte) Transaction_Date, a.dte, a.activity, a.part, 
  a.loading, a.user_name, a.device, a.fromloc, a.toloc, a.to_area, b.NAME||' '||b.Surname 
  Name, a.qty, DECODE(d.workarea, 'Tables','Wood','Metal')Material

  from table a,  table b, table c, table d

  where 
  (a.toloc = d.storage and a.part = c.part and c.region = 'Country1' and a.dte > 
   trunc(sysdate) - '9' and a.region = 'Country1' and a.activity = 'IDENTIFY' and 
  a.user_name = b.user_name and d.maxarea <> 0 )

但是我建议使用SQL92的联接,而不是SQL89格式的联接,以便于阅读