DISTINCT只有一列

时间:2014-06-19 13:53:48

标签: sql distinct

我正在使用查询并尝试修改它,以便它只返回不同的" lodnum"其中有超过2个所说的" lodnum"。

我查看了ROW_NUMBER()OVER / PARTITIONS。我似乎无法让它做我想做的事。

查询是:(抱歉格式化)

SELECT i.lodnum,
      i.prtnum,
      i.lotnum,
      sum(i.untqty),
      i.ftpcod,
      i.invsts
      FROM inventory_view i,
               locmst m
      WHERE i.stoloc = m.stoloc
      AND m.arecod = 'PART-HSY'
      AND i.prtnum NOT IN (SELECT i2.prtnum
                                       FROM inventory_view i2,
                                                locmst m2
                                       WHERE i2.stoloc = m2.stoloc
                                       AND m2.arecod = 'PART-HSY'
                                       AND i2.lotnum = i.lotnum
                                       AND i2.invsts = i.invsts
                                       GROUP BY i2.prtnum
                                       HAVING COUNT(*) = 1)
      AND i.lodnum IN (SELECT i3.lodnum FROM inventory_view i3, locmst m3
                                       WHERE i3.stoloc = m3.stoloc
                                       AND m3.arecod = 'PART-HSY'
                                       AND i3.lotnum = i.lotnum
                                       AND i3.invsts = i.invsts
                                       GROUP BY i3.lodnum
                                       HAVING COUNT(*) > 1)

GROUP BY 
     i.lodnum,
    i.stoloc,
    i.prtnum,
    i.lotnum,
    i.ftpcod,
    i.invsts
ORDER BY 
    i.prtnum,
    i.lotnum,
    i.invsts

1 个答案:

答案 0 :(得分:0)

看起来像是:

with t as (
      YOUR QUERY HERE WITHOUT ORDER BY
     )
select t.*
from (select t.*, row_number() over (partition by lodnum order by lodnum) as seqnum
      from t
     ) t
where seqnum = 1
order by prtnum, lotnum, invsts;