November 6, 2017 at 5:03 am
hi guys
hope everyone is well,
I need some help
I need to manipulate some data so I can produce a performance report
I have the data below
I need to rearrange this data to look like the below
how can I do this? my sql knowledge isn't very good.
the table this data is coming from is called Data_Table
thank you for any help provides
November 6, 2017 at 5:16 am
Welcome to SSC. When posting data questions, it best to provide DDL and consumable sample data for other users. We don't have access to your server, or data, thus you need to supply it in a format that can be quickly and easily used by others. I've done this for you for this one:
I'll start looking at a solution for you now, but this'll help others answer as well (who may get to the end result faster than myself).
Thom~
Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
Larnu.uk
November 6, 2017 at 5:22 am
Ok, for a solution, this should get you what you're after. The method is called Cross Pivoting (because you use a CROSS APPLY to Pivot your data). If you have any questions on how it works, please do ask.
Thom~
Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
Larnu.uk
November 6, 2017 at 5:23 am
Hah. I was just working through this myself.
This seems to work, but using a table variable rather than your temporary table, Thom A.
DECLARE @DataTable TABLE
(
id INTEGER,
maindate DATE,
system VARCHAR(10),
comment VARCHAR(10),
type INTEGER,
lcount INTEGER,
nlcount INTEGER,
fcount INTEGER,
depid INTEGER
);
INSERT INTO @DataTable
VALUES
(11, '2017-11-05', 'red', NULL, 1, 5, 20, 3, 5),
(22, '2017-11-05', 'red', NULL, 2, 4, 1, 4, 7);
SELECT id,
maindate,
system,
comment,
x.Fields,
x.[Values],
depid
FROM @DataTable
CROSS APPLY
(
VALUES
('lcount', lcount),
('nlcount', nlcount),
('fcount', fcount)
) x (Fields, [Values]);
--edit: tweaked cross apply field names to match your requirement. Note use of square brackets around keyword
Technique lifted shamelessly from Kenneth Fisher's blog post "unpivot a table using cross apply"
Thomas Rushton
blog: https://thelonedba.wordpress.com
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply