对聚合值SQL的操作

时间:2017-11-14 15:45:19

标签: sql aggregate

我希望按周计算我的收入,然后按周计算我的费用。

select *
from (select sum(revenue) earned
            , week(transaction_date) earned_week

    from mytable

    where year(transaction_date) = '1988'

    group by week(transaction_date)


    ) moneyin


    inner join
        (select sum(expenses) spent
                  , week(expense_date) spent_week

          from mytable

          where year(expense_date) = '1988'

          group by week(expense_date)


          ) moneyout



    on moneyin.earned_week = moneyout.spent_week;

现在,我想添加一个列,其中包含货币收入和货币支出(赢得 - 支出的余额)之间的差异,以及相同的每周汇总。但我没有抓住我可以插入声明的级别。 有什么建议? 谢谢

2 个答案:

答案 0 :(得分:1)

您可以将moneyin和moneyout数据组用作任何其他表,因此下面的查询应该有效:

select * , moneyin.earned - moneyout.spent as Difference
    from (select sum(revenue) earned
                , week(transaction_date) earned_week

        from mytable

        where year(transaction_date) = '1988'

        group by week(transaction_date)


        ) moneyin


        inner join
            (select sum(expenses) spent
                      , week(expense_date) spent_week

              from mytable

              where year(expense_date) = '1988'

              group by week(expense_date)


              ) moneyout



        on moneyin.earned_week = moneyout.spent_week;

答案 1 :(得分:1)

我会说你应该能够在你的陈述的顶部做到这一点,而不是选择*

类似于:

import torch
import time
def fitness(x):
     return torch.pow(x, 2)

def velocity(v, gxbest, pxbest, pybest, x, pop):
     return torch.rand(pop).type(dtype)*v + \
            torch.rand(pop).type(dtype)*(pxbest - x) + \
            torch.rand(pop).type(dtype)*(gxbest.expand(x.size(0)) - x)

dtype = torch.cuda.FloatTensor 
def main():

    pop, xmax, xmin, niter = 300000, 50, -50, 100
    v                      = torch.rand(pop).type(dtype)
    x                      = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
    y                      = fitness(x)
    [miny, indexminy]      = y.min(0)
    gxbest                 = x[indexminy] 
    pxbest                 = x
    pybest                 = y

    for K in range(niter):

        vnext = velocity(v, gxbest, pxbest, pybest, x, pop)

        xnext = x + vnext
        ynext = fitness(x)
        [minynext, indexminynext]  = ynext.min(0)

        if (minynext < miny):
            miny   = minynext
            gxbest = xnext[indexminynext]

        indexpbest         = (ynext < pybest)
        pxbest[indexpbest] = xnext[indexpbest]
        pybest[indexpbest] = ynext[indexpbest]
        x                  = xnext
        v                  = vnext
main()