关于sql server:如何基于两列过滤sql表中的多行

how to filter multiple rows in a sql table based on two columns

1
2
3
4
5
6
7
ID     |Number|Qty|OrderNumber|Date
456-98A|746-96|0.1|00         |2015-01-01
456-98A|746-96|0.1|00         |2015-01-01
456-98A|746-96|0.1|00         |2015-01-01
456-98A|746-96|0.1|00         |2015-01-01
456-98A|321-96|0.3|05         |2015-01-01
456-98A|321-96|0.3|05         |2015-01-01

sql中的上面的表给了我多个相同ID的行。我如何过滤这些数据,这样如果Number和orderNumber相同,那么它必须只为我提供一行而不是多个值。例如预期的结果 将会

1
2
3
ID     |Number|Qty|OrderNumber|Date
456-98A|746-96|0.1|00         |2015-01-01
456-98A|321-96|0.3|05         |2015-01-01


您可以按列分组,也可以全部或不同。

1
2
select ID, Number, Qty, OrderNumber, Date from YourTable
group by ID, Number, Qty, OrderNumber, Date

如果您可以使用临时表,则可以执行以下操作:

1
2
3
4
5
CREATE TABLE #tempo
  ([rowNum] identity, [ID] varchar(7), [Number] varchar(6), [Qty] int, [OrderNumber] int, [Date] datetime);

INSERT INTO #tempo ([ID], [Number], [Qty], [OrderNumber], [Date])
SELECT [ID], [Number], [Qty], [OrderNumber], [Date] FROM yourtable

并获得正确的行:

1
2
3
4
5
6
7
8
SELECT t1.[ID], t1.[Number], t1.[Qty], t1.[OrderNumber], t1.[Date]
FROM #tempo AS t1
WHERE NOT EXISTS (SELECT 1
    FROM #tempo AS t2
    WHERE t2.ID = t1.ID
      AND t2.Number = t2.Number
      -- **and other columns if needed**    
      AND t2.RowNum > t1.RowNum)


您可以像这样使用ROW_NUMBER()PARTITION BY

SQL小提琴

询问

1
2
3
4
5
6
7
SELECT ID, Number,Qty,OrderNumber,Date
FROM
(
SELECT ID, Number,Qty,OrderNumber,Date,ROW_NUMBER()OVER(PARTITION BY Number, orderNumber ORDER BY ID ) as rn
FROM yourTable
)yourTable
WHERE rn = 1

样本数据

1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE yourTable
    ([ID] varchar(7), [Number] varchar(6), [Qty] int, [OrderNumber] int, [Date] datetime);

INSERT INTO yourTable
    ([ID], [Number], [Qty], [OrderNumber], [Date])
VALUES
    ('456-98A', '746-96', 0.1, 00, '2015-01-01 00:00:00'),
    ('456-98A', '746-96', 0.1, 00, '2015-01-01 00:00:00'),
    ('456-98A', '746-96', 0.1, 00, '2015-01-01 00:00:00'),
    ('456-98A', '746-96', 0.1, 00, '2015-01-01 00:00:00'),
    ('456-98A', '321-96', 0.3, 05, '2015-01-01 00:00:00'),
    ('456-98A', '321-96', 0.3, 05, '2015-01-01 00:00:00');

产量

1
2
3
ID  Number  Qty OrderNumber Date
456-98A 321-96  0   5   2015-01-01 00:00:00.000
456-98A 746-96  0   0   2015-01-01 00:00:00.000