Crosstab function

I have data in a table like this:

Level1      Level2       Level3       Level4       Error
--------      --------       --------       --------       ------
Red1        Red2          Red3         Red4         E
Red1        Red2          Red3         Red4         E
Red1        Red2          Red3         Red4         E
Red1        Red2          Red3         Red4         A
Red1        Red2          Red3         Red4         A
Red1        Red2          Red3         Blue4        E
Red1        Red2          Blue3        Blue4        W
Red1        Red2          Blue3        Blue4        W
Red1        Red2          Red3         Blue4        A

I need a function to give a cross tab counts result like the following:

Level1      Level2       Level3       Level4       Error_A     Error_E      Error_W
--------      --------       --------       --------       ---------      ---------      ----------
Red1        Red2          Red3         Red4         2                3
Red1        Red2          Red3         Blue4         1                1
Red1        Red2          Blue3        Blue4                                              2
FairfieldAsked:
Who is Participating?
 
tigin44Connect With a Mentor Commented:
try this
select level1, level2, level3, level4,
   sum(case when error = 'A' tthen 1 else 0 end) as error_A,
   sum(case when error = 'E' tthen 1 else 0 end) as error_E,
   sum(case when error = 'W' tthen 1 else 0 end) as error_W
from yourTbale
group by level1, level2, level3, level4

Open in new window

0
 
FairfieldAuthor Commented:
Do I use this in a function or as a select statement in a query?  If in a function, can you tell me how to use it?
0
 
Raja Jegan RSQL Server DBA & ArchitectCommented:
Use Pivot Function for better performance
SELECT Level1, Level2, Level3, Level4, [A] AS Error_A,[E] AS Error_E,[W] AS Error_W
FROM (
SELECT Level1, Level2, Level3, Level4, Error
FROM urtable) ps
PIVOT
(count (level1)
FOR Error IN
( [A], [E], [W])
) AS pvt

Open in new window

0
[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

 
Raja Jegan RSQL Server DBA & ArchitectCommented:
You can use this as part of your SELECT statement itself. No Need for any functions to handle this
0
 
tigin44Commented:
you can use as you needed.
if you want you may put the select staement into a funtion and call taht function when you need it.
0
 
FairfieldAuthor Commented:
rrjegan17:
I am receiving and error when using your solution



Msg 207, Level 16, State 1, Line 1
Invalid column name 'Level1'.
0
All Courses

From novice to tech pro — start learning today.