Click here to Skip to main content
15,890,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Headings1 Headings2
--------------------------
Amikacin Sensitivity
Ampicillin Resistant
Cefadroxil Intermediate
Cefoperazone Resistant
Chloramphenicol Resistant
GENTAMYCIN Sensitivity
Netromycin Sensitivity
Rifamycin Sensitivity
Teicoplanin Resistant

I want to convert the above result like :

Sensitivity Resistant Intermediate
-------------------------------------------------------
Amikacin Ampicillin Cefadroxil
GENTAMYCIN Cefoperazone
Netromycin Chloramphenicol
Rifamycin Teicoplanin

What I have tried:

I've tried to query use pivot query but the value have to use aggregate function and the result is not appropriate. what should I do?
Posted
Updated 26-Jun-17 0:05am

1 solution

CREATE TABLE #thetable 
( id            INT IDENTITY(1,1) NOT NULL ,
headings1           VARCHAR(100),
headings2           VARCHAR(100),
)

INSERT INTO #thetable (headings1, headings2) VALUES ('Amikacin','Sensitivity')
INSERT INTO #thetable (headings1, headings2) VALUES ('Ampicillin','Resistant')
INSERT INTO #thetable (headings1, headings2) VALUES ('Cefadroxil','Intermediate')
INSERT INTO #thetable (headings1, headings2) VALUES ('Cefoperazone','Resistant')
INSERT INTO #thetable (headings1, headings2) VALUES ('Chloramphenicol','Resistant')
INSERT INTO #thetable (headings1, headings2) VALUES ('Netromycin','Sensitivity')

SELECT * FROM #thetable

-- this will work if you don't care about the NULL values and the position of the itmes
SELECT
  CASE WHEN headings2 = 'Sensitivity' THEN headings1 END AS 'Sensitivity'
  ,CASE WHEN headings2 = 'Resistant' THEN headings1 END AS 'Resistant'
  ,CASE WHEN headings2 = 'Intermediate' THEN headings1 END AS 'Intermediate'  
FROM  #thetable


-- this will have all NULL values at the bottom
SELECT
     t1.[Sensitivity]
	 ,t2.[Resistant]
	 ,t3.[Intermediate]
  FROM
( 
SELECT
  ROW_NUMBER() OVER (ORDER BY headings1) AS rn
  ,headings1 AS 'Sensitivity'
FROM  #thetable
WHERE headings2 = 'Sensitivity' 
) t1 FULL JOIN
(
SELECT
   ROW_NUMBER() OVER (ORDER BY headings1) AS rn
  ,headings1 AS  'Resistant'
FROM  #thetable
WHERE headings2 = 'Resistant' 
) t2 ON t1.rn = t2.rn  FULL JOIN
(
SELECT
   ROW_NUMBER() OVER (ORDER BY headings1) AS rn
  ,headings1 AS 'Intermediate'  
FROM  #thetable
WHERE headings2 = 'Intermediate' 
) t3 ON t1.rn = t3.rn
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900