March 7, 2016 at 11:05 pm
Hi I have table like
customerid 101
customernameRam
gender Male
married Y
customerid 102
customernameSham
gender Male
married Y
customerid 103
customernameTom
gender Male
married N
But I want the result set like below
customerid customername gender Married
101 ram Male Y
102 sham Male Y
103 tom Male N
Please help to do this. If the script for dynamic columns is more appreciate.
March 8, 2016 at 12:43 am
Could you please provide DDL (create table), sample data (as insert script) and expected output from that sample?
😎
March 8, 2016 at 12:54 am
Can you provide more information please, I dont fully understand what the problem is?
March 8, 2016 at 7:55 am
You have to remember that tables are sets and therefore inherently UNORDERED. You cannot depend on the presentation order to produce your desired results and there is no field that we can use to either link or order your records to reliably produce your desired results.
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA
March 8, 2016 at 8:13 am
You got yourself into trouble because your table isn't normalized. This is just a bad way of storing data. Now assuming you had a unique ID per person in that table you could use a cross tab to do what you want. Note how I created the sample data. In the future please add that with your question and you will see a huge difference in how people will be willing to help. Welcome to the forums, cheers!
DECLARE @myTable TABLE (ID INT, SomeKey VARCHAR(50), SomeValue VARCHAR(20))
INSERT INTO @myTable
VALUES (1, 'customerid','101'),(1, 'customername','Ram'),(1, 'gender','Male'),(1, 'married','Y'),(2, 'customerid','102'),(2, 'customername','Sham'),(2, 'gender','Male'),(2, 'married','Y'),(3, 'customerid','103'),(3, 'customername','Tom'),(3, 'gender','Male'),(3, 'married','N')
SELECT * FROM @myTable
SELECT
ID,
MAX(CASE WHEN SomeKey = 'customerid' THEN SomeValue END) AS CustomerID,
MAX(CASE WHEN SomeKey = 'customername' THEN SomeValue END) AS CustomerName,
MAX(CASE WHEN SomeKey = 'gender' THEN SomeValue END) AS Gender,
MAX(CASE WHEN SomeKey = 'married' THEN SomeValue END) AS Married
FROM
@myTable
GROUP BY
ID
March 9, 2016 at 5:25 am
does the relate to your previous question
http://www.sqlservercentral.com/Forums/FindPost1767204.aspx
________________________________________________________________
you can lead a user to data....but you cannot make them think
and remember....every day is a school day
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply