Oracle SQL Distinct子句不提供不同的值

时间:2013-12-05 18:26:30

标签: sql oracle duplicates distinct clause

我有一个脚本,当我尝试在库存中选择所述位置数量为< = 5的位置时。查询已完成,现在我正在尝试进行一些微调,并且我现在遇到的是当我使用distinct子句时,我仍然在同一列中接收重复记录。我知道第一列旁边的列是唯一的,但我认为区别不同,一列将翻转到与该列相关的下一列。

这是我的代码:

select DISTINCT bin.scannable_id as bin, 
  bi.bin_id as case1,
  pallet.scannable_id as pallet,       
 -- bi.isbn as fcsku, 
  nvl(fs.asin,bi.isbn) as asin, 
  sum(bi.quantity) as quantity, 
  pallet.creation_date as received_date 
  from containers bin 
  join containers pallet on pallet.containing_container_id = bin.container_id 
  join containers case on case.containing_container_id = pallet.container_id 
  join bin_items bi on bi.container_id = case.container_id 
  left join fcskus fs on fs.fcsku = bi.isbn 
  where bin.scannable_id like 'R-1-T%'
  and bi.quantity <= '5'
  group by bin.scannable_id, pallet.scannable_id, bi.bin_id, bi.owner,bi.isbn,nvl(fs.asin,bi.isbn), pallet.creation_date
  order by sum(bi.quantity);

我的输出,显然在scannable_id列中显示重复记录: enter image description here

格式正确感谢conrad。

    select DISTINCT bin.scannable_id as bin,   
  pallet.scannable_id as pallet,       
   nvl(fs.asin,bi.isbn) as asin, 
  sum(bi.quantity) as quantity   
  from containers bin 
  join containers pallet on pallet.containing_container_id = bin.container_id 
  join containers case on case.containing_container_id = pallet.container_id 
  join bin_items bi on bi.container_id = case.container_id 
  left join fcskus fs on fs.fcsku = bi.isbn 
  where bin.scannable_id like 'R-1-T%'
  having sum(bi.quantity) <= '5'
  group by bin.scannable_id, pallet.scannable_id, nvl(fs.asin,bi.isbn), bi.quantity
  order by sum(bi.quantity);

2 个答案:

答案 0 :(得分:1)

如上所述,如果您有DISTINCT声明,则不需要group by。并格式化您的日期字段,因为根据您的oracle客户端配置,它不会显示整个日期格式(例如日期时间)。所以试试这个:

select  bin.scannable_id as bin, 
        bi.bin_id as case1,
        pallet.scannable_id as pallet,       
        nvl(fs.asin,bi.isbn) as asin, 
        to_char(pallet.creation_date, 'yyyy-mm-dd') as received_date 
        sum(bi.quantity) as quantity, 
  from containers bin 
     join containers pallet on pallet.containing_container_id = bin.container_id 
     join containers case on case.containing_container_id = pallet.container_id 
     join bin_items bi on bi.container_id = case.container_id 
     left join fcskus fs on fs.fcsku = bi.isbn 
 where bin.scannable_id like 'R-1-T%'
   and bi.quantity <= '5'
 group by bin.scannable_id, 
          pallet.scannable_id, 
          bi.bin_id, 
          bi.owner,
          bi.isbn,
          nvl(fs.asin,bi.isbn), 
          to_char(pallet.creation_date, 'yyyy-mm-dd')
 order by sum(bi.quantity);

答案 1 :(得分:0)

每行的

bi.bin_id不同,因此您的结果集中只有不同的结果。

  • distinct已应用于最终可见结果集(处理to_char等功能后)
  • 如果您已使用distinct表达式,则
  • group by是多余的

解决方案:从选择表达式中跳过bi.bin_id列。

你的逻辑也令人困惑。您想知道所有bi。*元素的SUM。为此,您不能按bi.bin_id分组,也不能分组bi表中的任何字段。这就是您的quantity结果始终为1的原因。