sql relation using with/without pivot to display dynamic columns
I have a table structure like below:
Table nam开发者_Python百科e: questionsTable and the date is look like
qid qName
1 Enter your licence number.
2 What is your favaorite sport.
3 Enter your attendee name
Another Table name: tbl_Answer and the data is look like
qid attendeeid Answer
1 2349 45645645
2 2349 Cricket
3 2350 James
2 2350 Chess
1 2350 858585
Now I want to display my output to look like this:
attendeeid questionlable answer questionlable answer questionlable answer
2349 Enteryourlicencenumber 45645645 Whatisyourfavaoritesport Cricket
2350 Enteryourlicencenumber 858585 What is your favaorite sport hockey Enteryourattendeename James
Here I want to display question lable dynamic because here sample I have taken 3 qid.
SQL Server doesn't have anything (as far as I know) that can pivot to a dynamic number of columns.
Additionally, you'll find that you need different names for the different columns, and so there would need to be a mechanism for dynamically naming columns.
The closest you may be able to get is to write some SQL that writes SQL and then execute that. I certainly wouldn't want to go that route.
A better approach, in my opinion, is to pivot the data in your client. As a general principle, I try to not deal with formating/layout/presentation issues on the SQL Server. I find that it is better to simply ensure that the results provided give complete, accurate and consistent information, so as to enable the application to do what it wants.
(This enables your SQL to be about data in a way that is agnostic as to it's use. This means that changes to the application are much less likely to require changes to the SQL.)
精彩评论