日期:2014-05-17 浏览次数:20581 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-09-27 16:09:38
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
-- Jun 10 2013 20:09:10
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[额度明细表]
if object_id('[额度明细表]') is not null drop table [额度明细表]
go
create table [额度明细表]([员工ID] varchar(6),[时间] datetime,[额度] int,[剩余额度] int)
insert [额度明细表]
select '000101','2013-07-01',8,8 union all
select '000101','2013-07-09',8,8 union all
select '000101','2013-08-10',4,4 union all
select '000101','2013-08-16',8,8 union all
select '000101','2013-09-05',8,8
--> 测试数据:[使用额度表]
if object_id('[使用额度表]') is not null drop table [使用额度表]
go
create table [使用额度表]([员工ID] varchar(6),[使用额度] int)
insert [使用额度表]
select '000101',17
--------------开始查询--------------------------
;WITH CTE AS (
select A.员工ID,时间,额度,剩余额度,[使用额度],ROW_NUMBER()OVER(ORDER BY [时间])pid
from [额度明细表] A INNER JOIN [使用额度表] B ON A.员工ID=B.员工ID),
CTE2 AS (
SELECT 员工ID,时间,额度,CASE WHEN [使用额度]>=额度 THEN 额度 ELSE 额度-[使用额度] END 剩余额度,[使用额度]-额度 AS [使用额度],PID
FROM CTE
WHERE PID=1
UNION ALL
SELECT A.员工ID,A.时间,A.额度,CASE WHEN B.[使用额度]>=A.额度 THEN A.额度 WHEN B.[使用额度]>=0 THEN B.[使用额度] ELSE 0 END 剩余额度,B.使用额度-A.额度 AS [使用额度],A.PID
FROM CTE A INNER JOIN CTE2 B ON A.PID=B.PID+1
)
SELECT 员工ID,时间,额度,剩余额度 FROM CTE2
----------------结果----------------------------
/*
员工ID 时间 额度 剩余额度
------ ----------------------- ----------- -----------
000101 2013-07-01 00:00:00.000 8 8
000101 2013-07-09 00:00:00.000 8 8
000101 2013-08-10 00:00:00.000 4 1
000101 2013-08-16 00:00:00.000 8 0
000101 2013-09-05 00:00:00.000 8