我正在尝试删除在特定列中与另一行具有相同值的重复行。
输入
Shape Color Size Location
ball blue small s
circle green small n
triangle yellow large w
triangle red medium n
circle purple small n
ball orange small s
square green medium e
输出
Shape Color Size Location
ball blue small s
circle green small n
triangle yellow large w
triangle red medium n
square green medium e
基本上我想摆脱多余的行,其中1,3,4列的值与另一行的值相同
您可以使用窗口功能吗?
答案 0 :(得分:0)
您可以尝试此查询。编写一个子查询,并将Row_Number
与 windows函数一起使用。
select *
from (
SELECT *,ROW_NUMBER() OVER(PARTITION BY Shape,Size ORDER BY Shape) rn
FROM T
) t1
WHERE t1.rn =1
答案 1 :(得分:0)
如果您不关心返回哪种颜色,则可以执行此操作。此代码使用CTE添加行号,然后提取每个唯一Shape + Size + Location的第一条记录,并采用顶部的Color记录:
; WITH AllRecords
AS (
SELECT
Shape
, Color
, Size
, Location
, RowNum = ROW_NUMBER() OVER(PARTITION BY Shape, Size, Location ORDER BY Color)
FROM YourTable
)
SELECT *
FROM AllRecords
WHERE AllRecords.RowNum = 1;
答案 2 :(得分:0)
您只需要添加group by子句。
select shape,size,color,location
from t
group by shape,size,color,location
答案 3 :(得分:0)
如果我正确阅读了您的问题,则想从表中删除重复的值。是的,Windows函数是执行此操作的更有效方法之一。
DECLARE @Input TABLE
(
Shape varchar(20),
Color varchar(20),
Size varchar(20),
Location char(1)
);
INSERT INTO @Input
VALUES
('ball' ,'blue' ,'small' ,'s'),
('circle' ,'green' ,'small' ,'n'),
('triangle' ,'yellow' ,'large' ,'w'),
('triangle' ,'red' ,'medium' ,'n'),
('circle' ,'purple' ,'small' ,'n'),
('ball' ,'orange' ,'small' ,'s'),
('square' ,'green' ,'medium' ,'e');
WITH cte AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY Shape, Size, Location ORDER BY (SELECT 0)) AS RowNum,
Shape,
Size,
Location
FROM @Input
)
DELETE
FROM cte
WHERE RowNum > 1;
SELECT
*
FROM
@Input;
--Output
+----------+--------+--------+----------+
| Shape | Color | Size | Location |
+----------+--------+--------+----------+
| ball | blue | small | s |
| triangle | yellow | large | w |
| triangle | red | medium | n |
| circle | purple | small | n |
| square | green | medium | e |
+----------+--------+--------+----------+