如何选择彼此对应的列值?

时间:2016-02-04 20:09:57

标签: sql sql-server-2012 group-by correlated-subquery sql-subselect

我有一个结果集,对于相同的ID,我有三行,因为有不同的FirstName,LastName和BranchName。

例如:

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

我希望这个ID的一行显示任何BranchName,但是它应该显示该BranchName的相应FirstName和LastName以及(Balance的余额)不是随机组合,即它可以是Debra Hays,使用Dayton作为branchname而不是Lynden作为BranchName。

基本上,FirstName,LastName和BranchName应该彼此对应,而不是任何名字或姓氏组合。我想知道我们怎么能实现这个目标?

预期输出:

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

或者

ID  FirstName LastName BranchName Sum(balance) 
101 Daniel    Brinkman Lynden     750 

1 个答案:

答案 0 :(得分:2)

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;

输出:

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