0

I currently have a data set that has all information row-wise.

For example:

EmpID Dept ItemCode IssueDate
10001 ELECT 400001 28/02/2020
10002 MECH 400001 20/03/2020
10001 ELECT 400001 01/03/2021
10001 ELECT 400001 05/04/2022
10002 MECH 400001 28/04/2021
10003 CIVIL 400001 28/02/2022

Output needs to be like this:

EmpID Dept ItemCode 2020 2021 2022
10001 ELECT 400001 28/02/2020 01/03/2021 05/04/2022
10002 MECH 400001 20/03/2020 28/04/2021
10003 CIVIL 400001 28/02/2022

I want to display the output for the last 3 years' data for employees. I would like to write a query in a generic way that displays the last 3 years' data.

1

1 Answer 1

1

it is called pivot, but as i don't have a 2012 sql server i don't know if pivoz was already there.

so you can use at least the classical way

CREATE TABLE items (
  "EmpID" INTEGER,
  "Dept" VARCHAR(5),
  "ItemCode" INTEGER,
  "IssueDate"  VARCHAR(10)
);

INSERT INTO items
  ("EmpID", "Dept", "ItemCode", "IssueDate")
VALUES
  ('10001', 'ELECT', '400001', '28/02/2020'),
  ('10002', 'MECH', '400001', '20/03/2020'),
  ('10001', 'ELECT', '400001', '01/03/2021'),
  ('10001', 'ELECT', '400001', '05/04/2022'),
  ('10002', 'MECH', '400001', '28/04/2021'),
  ('10003', 'CIVIL', '400001', '28/02/2022');
GO
SELECT
"EmpID", "Dept", "ItemCode"
, MAX(CASE WHEN YEAR(convert(DATE,"IssueDate", 103)) = 2020 THEN "IssueDate" ELSE NULL END) '2020'
, MAX(CASE WHEN YEAR(convert(DATE,"IssueDate", 103)) = 2021 THEN "IssueDate" ELSE NULL END) '2021'
, MAX(CASE WHEN YEAR(convert(DATE,"IssueDate", 103)) = 2022 THEN "IssueDate" ELSE NULL END) '20212'
FROM [items]
GROUP BY "EmpID", "Dept", "ItemCode"
GO
EmpID | Dept  | ItemCode | 2020       | 2021       | 20212     
----: | :---- | -------: | :--------- | :--------- | :---------
10001 | ELECT |   400001 | 28/02/2020 | 01/03/2021 | 05/04/2022
10002 | MECH  |   400001 | 20/03/2020 | 28/04/2021 | null      
10003 | CIVIL |   400001 | null       | null       | 28/02/2022

db<>fiddle here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.