- DROP TABLE [dbo].[KBOrder]
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[KBOrder](
- [COMPANY] [varchar](50) NULL,
- [PERSON] [varchar](50) NULL,
- [JIE] [numeric](18, 2) NULL,
- [DAI] [numeric](18, 2) NULL,
- [YU] [numeric](18, 2) NULL
- ) ON [PRIMARY]
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'A', N'张三', CAST(1.00 AS Numeric(18, 2)), CAST(10.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'A', N'张三', CAST(2.00 AS Numeric(18, 2)), CAST(9.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'A', N'张三', CAST(3.00 AS Numeric(18, 2)), CAST(8.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'B', N'李四', CAST(4.00 AS Numeric(18, 2)), CAST(7.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'B', N'李四', CAST(5.00 AS Numeric(18, 2)), CAST(6.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'A', N'王五', CAST(6.00 AS Numeric(18, 2)), CAST(5.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'A', N'王五', CAST(7.00 AS Numeric(18, 2)), CAST(4.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'A', N'王五', CAST(8.00 AS Numeric(18, 2)), CAST(3.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'B', N'赵六', CAST(9.00 AS Numeric(18, 2)), CAST(2.00 AS Numeric(18, 2)), NULL)
- GO
- INSERT [dbo].[KBOrder] ([COMPANY], [PERSON], [DAI], [JIE], [YU]) VALUES (N'B', N'赵六', CAST(10.00 AS Numeric(18, 2)), CAST(1.00 AS Numeric(18, 2)), NULL)
- GO
- WITH C AS(
- SELECT [COMPANY]
- ,[PERSON]
- ,[JIE]
- ,[DAI]
- ,[YU]
- ,SUM([JIE]) OVER(PARTITION BY COMPANY,PERSON
- ORDER BY COMPANY,PERSON
- ROWS BETWEEN UNBOUNDED PRECEDING
- AND CURRENT ROW) RunSumJIE
- ,SUM(DAI) OVER(PARTITION BY COMPANY,PERSON ORDER BY COMPANY,PERSON) SumDai
- ,SUM([JIE]) OVER(PARTITION BY COMPANY,PERSON
- ORDER BY COMPANY,PERSON
- ROWS BETWEEN UNBOUNDED PRECEDING
- AND CURRENT ROW)
- - SUM(DAI) OVER(PARTITION BY COMPANY,PERSON ORDER BY COMPANY,PERSON) CHA
- FROM [dbo].[KBOrder]
- )
- SELECT C.COMPANY,C.PERSON,C.JIE,C.DAI,C.YU,C.RunSumJIE,C.SumDai,C.CHA
- ,CASE WHEN C.CHA <= 0 THEN 0 WHEN C.CHA > 0 AND C.CHA < C.JIE THEN C.CHA WHEN C.CHA > 0 AND C.CHA > C.JIE THEN C.JIE END
- FROM C
复制代码
|
|
hessen