我有以下查询:(SQL Server)
SELECT
sched_ship, loc_desc,
bag_no, lotnumber
FROM
[My-Table]
WHERE
loc_no LIKE '171'
AND cust_name NOT LIKE 'PCI'
AND pci_pn NOT LIKE '%TEST%'
ORDER BY sched_ship
从这个查询中,我需要删除重复项,只保留“bag_no”的第一个结果。
IE:这个(sched_ship与我正在寻找的排序无关,无视它)
sched_ship | loc_desc | bag_no | lotnumber
-----------+----------+--------+----------
1-05-2014 | loc 1 | G123 | 2345-35
3-22-2014 | loc 1 | H347 | 9583-68
4-16-2014 | loc 1 | G123 | 2745-34
4-25-2014 | loc 1 | J846 | 5726-90
4-26-2014 | loc 1 | G123 | 1756-28
5-12-2014 | loc 1 | J846 | 2847-68
返回:( sched_ship与我正在寻找的排序无关,无视它)
sched_ship | loc_desc | bag_no | lotnumber
-----------+----------+--------+----------
1-05-2014 | loc 1 | G123 | 2345-35
3-22-2014 | loc 1 | H347 | 9583-68
4-25-2014 | loc 1 | J846 | 5726-90
(sched_ship与我正在寻找的排序无关,无视它)
我想要的只是获取我的查询结果,然后进一步过滤掉任何带有重复“bag_no”的行。
答案 0 :(得分:1)
您可以使用row_number()
然后使用where
选择第一条记录来执行此操作:
select sched_ship, loc_desc, bag_no, lotnumber
from (SELECT sched_ship, loc_desc, bag_no, lotnumber,
row_number() over (partition by bag_no order by sched_ship asc) as seqnum
FROM [My-Table]
WHERE loc_no LIKE '171' AND cust_name NOT LIKE 'PCI' AND pci_pn NOT LIKE '%TEST%'
) t
where seqnum = 1
ORDER BY sched_ship;
row_number()
为从1开始的一组行分配一个序号。该组由partition by
子句定义,因此具有相同bag_no
的所有行都在同一组中(在这种情况下)。该顺序基于order by
子句,因此sched_ship
的第一行的值为1. where
子句选择此行。
编辑:
您可以使用CTE执行此操作:
with t as (
SELECT sched_ship, loc_desc, bag_no, lotnumber,
row_number() over (partition by bag_no order by sched_ship asc) as seqnum
FROM [My-Table]
WHERE loc_no LIKE '171' AND cust_name NOT LIKE 'PCI' AND pci_pn NOT LIKE '%TEST%'
)
select sched_ship, loc_desc, bag_no, lotnumber
from t
where seqnum = 1
ORDER BY sched_ship;
答案 1 :(得分:0)
试试这个伙伴......
SELECT sched_ship, loc_desc, bag_no, lotnumber
FROM [My-Table]
WHERE sched_ship
IN (SELECT MIN(sched_ship) FROM [My-Table] GROUP BY bag_no)