Home > other >  Select single row from multiple duplicate rows with value 1 SQL query
Select single row from multiple duplicate rows with value 1 SQL query

Time:11-05

I need only one row from multiple duplicate rows but the value should not missed in others fields

Current table:

Name      ABC   XYZ APT STA ZIP
--------------------------------
Computer    0   0   0   0   0
Computer    0   0   0   1   0
Computer    0   0   0   0   0
Computer    1   0   0   0   0
Computer    0   0   0   0   0

Result I want:

Name      ABC   XYZ APT STA ZIP
-------------------------------- 
Computer    1   0   0   1   0

CodePudding user response:

As many already suggested, it is a trivial task.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, _Name VARCHAR(20), ABC INT, XYZ INT, APT INT, STA INT, ZIP INT);
INSERT @tbl (_Name, ABC, XYZ, APT, STA, ZIP) VALUES
('Computer', 0, 0, 0, 0, 0),
('Computer', 0, 0, 0, 1, 0),
('Computer', 0, 0, 0, 0, 0),
('Computer', 1, 0, 0, 0, 0),
('Computer', 0, 0, 0, 0, 0);
-- DDL and sample data population, end

SELECT _Name, MAX(ABC) ABC, MAX(XYZ) XYZ, MAX(APT) APT, MAX(STA) STA, MAX(ZIP) ZIP
FROM @tbl
GROUP BY _Name;

Output

_Name ABC XYZ APT STA ZIP
Computer 1 0 0 1 0
  • Related