简体   繁体   中英

SUM fields in SQL server depending on another field and using inner join

The title may be a bit vague, but let me explain:

I have a script that creates a database and two tables, one for transactions and one for accounts:

CREATE TABLE Transactions(
        transactionID VARCHAR(10),
        description VARCHAR(70),
        accountID VARCHAR(5) NOT NULL,
        amount MONEY NOT NULL

        CONSTRAINT transactionsPK
            PRIMARY KEY (transactionID)
)

CREATE TABLE Accounts(
        accountID VARCHAR(10),
        accountName VARCHAR(70) NOT NULL,
        bank VARCHAR(70) NOT NULL

        CONSTRAINT accountsPK
            PRIMARY KEY (accountID)
)

I would like to write a SELECT statement to list all of the fields in the accounts table, along with a total column. I thought I could use an INNER JOIN to only display each account, but I am not sure if DISTINCT would work better.

Its purpose is to SUM all of the transactions for each account, and place that amount in the row for the account itself.

I can achieve the product of listing the amount of each transaction, but not the SUM of all tansactions for each Account.

SELECT Accounts.accountID, Accounts.accountName, Accounts.bank, Transactions.amount
    FROM Accounts
    INNER JOIN Transactions
    ON Accounts.accountID = Transactions.accountID

Any help would be greatly appreciated.

You just need the SUM() function:

SELECT a.accountID, a.accountName, a.bank, SUM(t.amount)
FROM accounts a
INNER JOIN transactions t
ON a.accountID = t.accountID
GROUP BY a.accountID, a.accountName, a.bank

When you are done you need to group by the accountID. This will effectively sum each group (each account).

Here are some SQL aggregate functions for you.

I think this would help :

SELECT a.*,
       sumamt
FROM   Accounts a
       LEFT OUTER JOIN (SELECT accountID,
                               Sum(amount) sumamt
                        FROM   transactions
                        GROUP  BY accountID) AS t
                    ON a.accountID = t.accountID 

sample sql fiddle here

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