SQL multiple fields grouped, delete duplicate records, keep one of the smallest IDs

Source: Internet
Author: User

IF object_id('Carddetail') is  not NULL   DROP TABLECarddetailCREATE TABLECarddetail (IDINT IDENTITY(1,1)PRIMARY KEY, CardnoVARCHAR(8), NAMEVARCHAR( -), IdcardVARCHAR( -), CardstateCHAR(1)--card Status 1 Normal 2 logoff )  INSERTCarddetail (cardno,name,idcard,cardstate)VALUES ('001','Zhang San','31010',1), ('005','Zhang San','31010',1), ('002','John Doe','31011',1), ('003','Harry','31012',1), ('006','Zhang San','31010',0), ('004','Harry','31012',1), ('007','Ouyang','31013',1), ('008','Ouyang','31013',1)

--sql Writing requirements
--delete duplicates based on Idcard,cardstate, keeping the record with the smallest ID

-The end result is:
(1, ' 001 ', ' Zhang San ', ' 31010 ', 1),
(4, ' 003 ', ' Harry ', ' 31012 ', 1),
(7, ' 007 ', ' Ouyang ', ' 31013 ', 1),

Solve

 with  as (   Select  id,cardno,name,idcard,cardstate,      over byOrder   by as od   from  carddetail)Select*  fromwhere=1;

SQL multiple fields grouped, delete duplicate records, keep one of the smallest IDs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.