简体   繁体   中英

How do I select column values to be corresponding to each other?

I have a resultset where for the same ID I have three rows because there are different FirstName, LastName and BranchName.

For example:

ID  FirstName  LastName  BranchName Balance
101   Debra      Hays      Dayton   200
101   Daniel     Brinkman  Lynden   250
101   Daniel     Brinkman  HZBK     300

I want one row for this ID showing any BranchName but it should show corresponding FirstName and LastName for that BranchName and (sum of Balance) not random combination ie it can be Debra Hays with Dayton as branchname not Lynden as BranchName.

Basically the FirstName, LastName and BranchName should be corresponding to each other not any first or lastname combination. I was wondering how can we achieve that?

Expected output:

ID  FirstName LastName BranchName Sum(balance) 
101 Debra     Hays     Dayton     750 

Or

ID  FirstName LastName BranchName Sum(balance) 
101 Daniel    Brinkman Lynden     750 
DECLARE @data TABLE(ID INT,FirstName VARCHAR(128),LastName VARCHAR(128),BranchName VARCHAR(128),Balance INT);
INSERT INTO @data(ID,FirstName,LastName,BranchName,Balance)VALUES
    (101,'Debra','Hays','Dayton',200),
    (101,'Daniel','Brinkman','Lynden',250),
    (101,'Daniel','Brinkman','HZBK',300);

;WITH cte AS (
    SELECT
        ID,
        FirstName,
        LastName,
        BranchName,
        rn=ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FirstName,LastName,BranchName),
        Balance=SUM(Balance) OVER (PARTITION BY ID)
    FROM
        @data
)
SELECT
    ID,
    FirstName,
    LastName,
    BranchName,
    Balance
FROM
    cte
WHERE
    rn=1;

Output:

+-----+-----------+----------+------------+---------+
| ID  | FirstName | LastName | BranchName | Balance |
+-----+-----------+----------+------------+---------+
| 101 | Daniel    | Brinkman | HZBK       |     750 |
+-----+-----------+----------+------------+---------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM