从select语句在SQL Server中创建视图

时间:2015-03-18 06:54:00

标签: sql sql-server sql-server-2012

我有选择声明,以两种货币返回每天的收入或结果:

SELECT SUM(CASE
            WHEN C.Name LIKE 'B%' AND T.Income = 0 THEN 0-T.Amount
            WHEN C.Name LIKE 'B%' AND T.Income = 1 THEN T.Amount
            ELSE 0
            END) AS AmountBYR
      ,SUM(CASE
            WHEN C.Name LIKE 'U%' AND T.Income = 0 THEN 0-T.Amount
            WHEN C.Name LIKE 'U%' AND T.Income = 1 THEN T.Amount
            ELSE 0
            END) AS AmountUSD
      ,CR.Date
FROM [FinanceLabkovich].[dbo].[Transactions] T
JOIN [FinanceLabkovich].[dbo].[Bills] B ON B.BillID=T.BillID
JOIN [FinanceLabkovich].[dbo].[Currencies] C ON C.CurrencyID=B.CurrencyID
RIGHT JOIN [FinanceLabkovich].[dbo].[CurrencyRates] CR ON CR.Date=T.Date
GROUP BY CR.Date
ORDER BY CR.Date

http://img.prntscr.com/img?url=http://i.imgur.com/Dzla7rR.png

我需要创建一个视图,显示每个人每天总共有多少钱

http://img.prntscr.com/img?url=http://i.imgur.com/fU2bnM6.png

1 个答案:

答案 0 :(得分:1)

在SQL Server 2012及更高版本中,您可以使用运行总和来计算当前余额:

sum(column_name) over (order by date) as running_sum

要在一天结束时仅查找运行总和,您可以使用子查询:

select  *
from    (
        select  customer_id
        ,       sum(amount) over (
                    partition by customer_id
                    order by [date]) as balance
        ,       row_number() over (
                    partition by customer_id, cast([date] as date)
                    order by [date] desc) as rn
        from    Transactions
        ) as SubQueryAlias
 where  rn = 1 -- Only latest row per customer per day