简体   繁体   中英

SQL computed column for sum of data in another table

I have two tables:

  DiskUsage Table                               StatisticsTable
Server    DiskUsage(GB)                  Total Disk Usage        xxxx
   1         10
   2         212
   3         11

I need to create the "Total Disk Usage" as a column which works out the Sum of the "DiskUsage" column. This would need to be dynamic as more servers will be added overtime to the "DiskUsage" table.

I've done some looking into this - and I believe a Computed Column would be the easiest way to achieve this, but I'm not sure how to a). reference the other tables data or b). dynamically obtain the total of that column.

What is the issue with just running a query?

select sum(diskusage)
from diskusage;

This seems simple enough and unless you have millions of rows, performance should be quite fast.

Create a trigger

CREATE TRIGGER test
ON DiskUsage
after INSERT, UPDATE
AS
  BEGIN
      UPDATE StatisticsTable
      SET    TotalDiskUsage = (SELECT Sum(DiskUsage)
                               FROM   DiskUsage)
  END 

Or as Mentioned by King.code create a view instead of having a table

CREATE VIEW StatisticsTable
AS
  SELECT Sum(DiskUsage)
  FROM   DiskUsage 

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