Question

I want to create an SQL view based on the sum of some columns in another table. This is quite easy, however, I want the new view to contain multiple different sums based on the data in the other table:

Table1:
ID: Integer (PK, Autoenumerated)
CompanyID: Integer (Not the PK!)
Amount: Integer

Each CompanyID can have multiple different Amounts in the table, i want to sum all of these amounts.

View1:
TotalAmount: Integer
CompanyID: Integer

The CompanyID in the view should match the CompanyID as in Table1, but the TotalAmount should be the sum of all of the amounts found for that CompanyID in Table1.

Also any advice for simply getting better at queries? This one seems kind of simple now that I see it, but of course I could not envision it originally.

Was it helpful?

Solution

This query would sum per company. Is this what you want in your view?

CREEATE VIEW SumsView
AS
SELECT CompanyID
     , SUM(Amount) TotalAmount
  FROM Table1
 GROUP BY CompanyID

In the question you mention that you want the ID column to be included in the view but how do you relate the ID to the aggregated sum?

The only way I can think of is that you care to duplicate the sums, like this:

CREEATE VIEW SumsView
AS
  SELECT  T.ID
        , T.CompanyID
        , A.TotalAmount
    FROM Table1 T
    INNER JOIN (SELECT CompanyID
                     , SUM(Amount) TotalAmount
                  FROM Table1
                 GROUP BY CompanyID) A
            ON T.CompanyID = A.CompanyID

OTHER TIPS

create view V_AmountByCompany
as
select CompanyID, sum(Amount) as sumAmount
from YourTable
group by CompanyID

It wouldn't make much sense to get the Id by the way, as you have many Id by companyID : so which one would be kept ? If you really want it, you could choose MIN(ID) or MAX(ID) but once again, what for ?

You should do like below

create view newsumbycompanyid
as
select companyid,sum(amount) as newamount
from table1
group by companyid
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top