I'm using SQL Server 2008 R2, I have this simple table
What I was trying to do is make a selection from this table and get this following result
x | 1 | 2 | 3
--+------------+-------------+------------
1 | first 1 | first 2 | first 3
2 | Second 1 | second 2 | second 3
I thought that can be done with PIVOT
I don't know much about PIVOT
AND all my search result found using PIVOT with Count()
. SUM()
, AVG()
which will not work in my table since I'm trying to PIVOT
on a varchar
column
Question am I using the right function? Or is there something else I need to know to solve this issue? Any help will be appreciated
I tried this with no luck
PIVOT(count(x) FOR value IN ([1],[2],[3]) )as total
PIVOT(count(y) FOR value IN ([1],[2],[3]) )as total // This one is the nearest
of what i wand but instead of the column value values i get 0
Here is the query if any one to test it
CREATE TABLE #test (x int , y int , value Varchar(50))
INSERT INTO #test VALUES(1,51,'first 1')
INSERT INTO #test VALUES(1,52,'first 2')
INSERT INTO #test VALUES(1,53,'first 3')
INSERT INTO #test VALUES(2,51,'Second 1')
INSERT INTO #test VALUES(2,52,'Second 2')
INSERT INTO #test VALUES(2,53,'Second 3')
SELECT * FROM #test
PIVOT(count(y) FOR value IN ([1],[2],[3]) )as total
DROP TABLE #test
Key is to use the Max function for text fields.
Query:
Working demo
I give you a trick but it hasn't meaning.
You say
value IN ([1],[2],[3])
. This means "match if value is exactly equal to 1, 2 or 3". But in your table it never is. Something is not right there.When you are using the PIVOT function the values inside the IN clause need to match a value that you are selecting. Your current data does not include 1, 2, or 3. You can use
row_number()
to assign a value for eachx
:See SQL Fiddle with Demo. If you then have a unknown number of values for each
x
, then you will want to use dynamic SQL:See SQL Fiddle with Demo