Solved

Cross Tab in sql 2008

Posted on 2012-04-06
2
228 Views
Last Modified: 2012-06-27
I am new to SQL SERVER 2008. I have a table tblUserInterest (id, User_Id, Interest_word, Weight) And other table as tblUser (id, UserName, Password, UserType)

I have data in tblUserInterest as,
id  User_Id   Interest_word                     Weight
--------------------------------------------------------------------------------
1        3         www.cooltoad.com                   6
2        3         www.google.co.in                     3
3        2         www.cooltoad.com                   1
4        2         www.google.co.in                     18

User 2 : Swati
User 3 : Sonali
I want to attach a result to grid which should be in format


UserName       www.cooltoad.com        www.google.co.in                               
---------------------------------------------------------------------------------------------
Swati                          1                                  18
Sonali                         6                                    3

How it can be get this rows in table are tblUserInterest  can increase with diffrent Interest_word?

Thanks in Advance.
0
Comment
Question by:swatiadeshpande
2 Comments
 
LVL 42

Expert Comment

by:EugeneZ
ID: 37815824
use Pivot operator   (more Using PIVOT  http://msdn.microsoft.com/en-us/library/ms177410.aspx)

try this below basic  code  (if you need more - use dynamic code)



   SELECT *
   FROM (
   select case when USER_ID=2 then 'Swati'
              when USER_ID=3 then 'Sonali ' end UserName , Interest_word ,  Weight from tblUserInterest
   ) AS PivotData
   PIVOT (
     max(Weight)
     FOR Interest_word  IN (
       [www.cooltoad.com],[www.google.co.in]
     )
   ) AS PivotTable
0
 
LVL 7

Accepted Solution

by:
Cboudroz earned 500 total points
ID: 37816352
The only way I know without having to "hardcode" the Interest_word it's whit a loop and temp table.

I will be happy to see someone do it without a loop!!

CREATE TABLE tblUser 
(
	id int
	, username varchar(150)
)
CREATE TABLE tblUserInterest
(
	iUser_id int
	, Interest_word varchar(150)
	, Weight int
)

INSERT INTO tblUser
SELECT 1, 'TEST1' UNION ALL 
SELECT 2, 'TEST2' UNION ALL 
SELECT 3, 'TEST3' 

INSERT INTO tblUserInterest
SELECT 1, 'INTEREST1', 100 UNION ALL 
SELECT 1, 'INTEREST2', 150 UNION ALL 
SELECT 1, 'INTEREST3', 110 UNION ALL 
SELECT 2, 'INTEREST1', 110 UNION ALL 
SELECT 2, 'INTEREST3', 100 


DROP TABLE #final_Results
CREATE TABLE #final_Results
(
	iUser_id int
	, UserName varchar(150)
)

INSERT INTO #final_results
(
	iUser_id
	, UserName
)
SELECT DISTINCT
	id
	, UserName
FROM 
	tblUser 



DECLARE @Interest_word	VARCHAR(255)
DECLARE @TSQL			VARCHAR(MAX)

DECLARE cur_Interest	CURSOR
FOR 
	SELECT DISTINCT
		Interest_word
	FROM 
		tblUserInterest 

OPEN cur_Interest


FETCH NEXT FROM cur_Interest INTO @Interest_word
	


WHILE @@FETCH_STATUS = 0 
BEGIN 

	-- ADD Interest_word as column
	SET @TSQL = 'ALTER TABLE #final_Results ADD '+@Interest_word+' INT NULL'
	EXECUTE (@TSQL)
	
	-- UPDATE Weight
	SET @TSQL = 
	'
		UPDATE T
			SET '+@Interest_word+' = ISNULL(Weight,0)
		FROM 
			#final_results T
			LEFT JOIN tblUserInterest I
				ON I.iUser_Id = T.iUser_Id
				AND I.Interest_word = ''' + @Interest_word + ''' 
			
	'
	EXECUTE (@TSQL)
	

	FETCH NEXT FROM cur_Interest INTO @Interest_word
END

CLOSE cur_Interest
DEALLOCATE cur_Interest


SELECT 
	*
FROM 
	#final_results

Open in new window

0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Sql server function help 15 31
T-SQL: Do I need CLUSTERED here? 13 45
Update a text value in another table 10 40
Sql server get data from a usp to use in a usp 5 16
Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question