SQL:当一个单独的2列字段相等时,如何对一列中的字段求和

时间:2014-05-06 22:19:58

标签: sql sql-server

在sql server中我正在尝试向我的查询添加一个列,它将colC的字段汇总到colA和colB显示的重复条目。

示例:我想弄清楚每个人总共支付了多少钱。每条记录代表一个人所做的一笔付款。我如何找到每个人支付的总金额?

我的表格如下:

FName | LName  | $Paid
Bob   | Dole   | 1
Bob   | Dole   | 2.2
Bob   | Barker | 6
Bob   | Barker | 2
Bob   | Barker | 2
Herbie| Hancock| 14

我想要的结果是:

FName  | LName  | $Paid | sum ColC where FName and LName are duplicates
Bob    | Dole   | 1     | 3.2
Bob    | Dole   | 2.2   | 3.2
Bob    | Barker | 6     | 10
Bob    | Barker | 2     | 10
Bob    | Barker | 2     | 10
Herbie | Hancock| 14    | 14

第四列重复输出不是必需的。该表也将达到预期的结果:

FName  | LName   | sum ColC where FName and LName are duplicates
Bob    | Dole    | 3.2
Bob    | Barker  | 10
Herbie | Hancock | 14

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

您可以加入原始表格,将这些群组加入原始交易。

SELECT
    M.FName,
    M.LName,
    M.total_paid,
    X.SUM(ColC) AS total_paid

FROM
    MyTable M
    INNER JOIN 
    (
        SELECT
            FName,
            LName,
            SUM(ColC) AS total_paid
                    COUNT(ColC) num
        FROM
            MyTable
        GROUP BY
            FName,
            LName 
            HAVING 
                    COUNT(colc) > 1 -- only include places where there are duplicate?
    ) AS x ON X.FName = M.FName and X.LName = M.LName

答案 1 :(得分:1)

试试这个

SELECT
    FName,
    LName,
    SUM(ColC) AS total_paid
FROM
    whateverTable
GROUP BY
(
    FName,
    LName
);

答案 2 :(得分:1)

鉴于distinct关键字,替代方案可能效率不高,但请尝试此操作。


    CREATE TABLE PAID ( FName VARCHAR(12), LName VARCHAR(12), [$Paid] NUMERIC(10,2))

    INSERT INTO PAID (FName, LName, [$Paid]) VALUES ('Bob','Dole',1);
    INSERT INTO PAID (FName, LName, [$Paid]) VALUES ('Bob','Dole',2.2);
    INSERT INTO PAID (FName, LName, [$Paid]) VALUES ('Bob','Barker',6);
    INSERT INTO PAID (FName, LName, [$Paid]) VALUES ('Bob','Barker',2);
    INSERT INTO PAID (FName, LName, [$Paid]) VALUES ('Bob','Barker',2);
    INSERT INTO PAID (FName, LName, [$Paid]) VALUES ('Herbie','Hancock',14);


    SELECT DISTINCT
        FName,
        LName,
        SUM([$Paid])OVER(PARTITION BY FName + LName) AS total_paid
    FROM
        PAID
    ;

检查SQLFiddle