I've a requirement to get employee yearly wages increment column wise and before I get into, please see the below sample first:
Sample 1: 1 - 4 years increment
EmpID EmpName 1st Increment 2nd Increment 3rd Increment 4th Increment
1 John 1000 2000 3000 4000
2 Jack 2000 4000 8000 16000
Sample 2: 5 - 8 years increment
EmpID EmpName 1st Increment 2nd Increment 3rd Increment 4th Increment
1 John 5000 6000 7000 8000
2 Jack 32000 64000 128000 256000
I guess, I am able to make understand what's it actually. The columns 1 - 4 increments should be kept static and for 1 - 4 years increment, the 1st sample could be managed and I've tried a query but not that efficient: (The idea is to get the 1st, 2nd , 3rd, 4th rows of a specific id 1 for sample 1)
WITH CTE AS
(
SELECT
*,
ROW_NUMBER() OVER (ORDER BY EmpID ASC) as RowNum
FROM EmpIncrement
WHERE EmpID = 1
)
SELECT
CTE.EmpID AS ID, CTE.Amt AS Amount,
(CASE WHEN CTE.RowNum = 1 THEN CTE.Amt ELSE 0 END) AS '1st Increment',
(CASE WHEN CTE.RowNum = 2 THEN CTE.Amt ELSE 0 END) AS '2nd Increment'
FROM
CTE
WHERE
CTE.RowNum IN (1, 2)
This is what I've got:
In sample 2, when it comes to 5th increment, then the increment amount should be placed in the '1st Increment' column and the rest accordingly. There could be a good solution but can't get it done. Could be it done with an easy approach or any idea/sample would be appreciated. Thanks.
The table structures and sample are as follows (Script):
USE [Demo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Employee]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[NAME] [nvarchar](100) NULL,
[ADDRESS] [nvarchar](max) NULL,
[SALARY] [float] NULL,
CONSTRAINT [PK__Employee__3214EC2714270015]
PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Employee] ON
INSERT [dbo].[Employee] ([ID], [NAME], [ADDRESS], [SALARY])
VALUES (1, N'John', N'Germany', 12000)
INSERT [dbo].[Employee] ([ID], [NAME], [ADDRESS], [SALARY])
VALUES (2, N'Jack', N'France', 14000)
SET IDENTITY_INSERT [dbo].[Employee] OFF
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmpIncrement]
(
[IncrementID] [int] IDENTITY(1,1) NOT NULL,
[EmpID] [int] NULL,
[Amt] [float] NULL,
[IncrementDate] [datetime] NULL,
CONSTRAINT [PK_EmpIncrement]
PRIMARY KEY CLUSTERED ([IncrementID] ASC)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[EmpIncrement] ON
INSERT [dbo].[EmpIncrement] ([IncrementID], [EmpID], [Amt], [IncrementDate])
VALUES (1, 1, 2000, CAST(0x0000A6D800000000 AS DateTime))
INSERT [dbo].[EmpIncrement] ([IncrementID], [EmpID], [Amt], [IncrementDate])
VALUES (2, 2, 8000, CAST(0x0000A6D800000000 AS DateTime))
INSERT [dbo].[EmpIncrement] ([IncrementID], [EmpID], [Amt], [IncrementDate])
VALUES (3, 1, 1000, CAST(0x0000A56A00000000 AS DateTime))
INSERT [dbo].[EmpIncrement] ([IncrementID], [EmpID], [Amt], [IncrementDate])
VALUES (4, 2, 4000, CAST(0x0000A56A00000000 AS DateTime))
SET IDENTITY_INSERT [dbo].[EmpIncrement] OFF