SQL:如何返回一列,该列是另一列上返回的行的总和?

时间:2018-12-18 07:37:21

标签: sql

我有一张公司和发票表。我的查询求和了每个公司发票的总价值,以提供公司的“总销售额”。我要返回的是与同一查询中的其他公司相比,每个公司的销售额的+/-。

Select Company.name, sum(Invoice.total) as InvoiceTotal
From Company
Inner Join Invoice on Invoice.CompanyId = Company.Id
Group By Company.name

假设上述查询产生:

Company          InvoiceTotal
A                100
B                200
C                600

我希望其他列提供的金额高于或低于InvoiceTotal列的平均值:

Company          InvoiceTotal    Difference
A                100             -200
B                200             -100
C                600             300

如何在单个查询中提取该值?

4 个答案:

答案 0 :(得分:1)

如果您的数据库可以处理开窗平均数(大多数情况下可以做到),则可以使用开窗平均函数将其应用于发票总和,然后使用发票总和进行其余操作。

这是SQL Server的示例:

"implementation"

结果:

;WITH Data AS
(
    SELECT
        *
    FROM
        (
        VALUES
            ('a', 50),
            ('a', 25),
            ('a', 25),

            ('b', 125),
            ('b', 75),

            ('c', 275),
            ('c', 50),
            ('c', 75),
            ('c', 200)) V(Company, Invoice)
)
SELECT
    Company = V.Company,
    Invoice = SUM(V.Invoice),
    AverageAcrossAllCompanies = AVG(SUM(V.Invoice)) OVER (),
    AverageInvoiceDifference = SUM(V.Invoice) - AVG(SUM(V.Invoice)) OVER ()
FROM
    Data AS V
GROUP BY
    V.Company

答案 1 :(得分:1)

假设您的数据库支持CTE

with total as (
    select avg(invoicetotal) totalsum
from table_name)
    select t.company, 
           t.invoicetotal, 
           t.invoicetotal - total.totalsum
from table_name t, total

Company INVOICETOTAL    T.INVOICETOTAL-TOTAL.TOTALSUM
A        100            -200
B        200            -100
C        600             300

答案 2 :(得分:0)

这是获取所需差异的另一种方法

Select
    name,
    InvoiceTotal,
    InvoiceTotal - avg(InvoiceTotal) as Difference
From
    (Select Company.name, sum(Invoice.total) as InvoiceTotal
    From Company
    Inner Join Invoice on Invoice.CompanyId = Company.Id
    Group By Company.name)
group by name, InvoiceTotal

答案 3 :(得分:0)

可以使用以下查询获得结果:

ssh_conn_id='my-conn-id'