March 26, 2013 at 11:06 am
hi, is it possible to make a query that will turn a result set into a crosstab and it will automatically know how many columns are needed, but WITHOUT using the Pivot function?
here is a table and data to illustrate what i'm talking about:
CREATE TABLE Lines
(
line varchar(5) NULL,
stopid varchar(5) NULL,
boardings int NULL
)
insert into lines (line, stopid, boardings)
values (2,1,58)
insert into lines (line, stopid, boardings)
values (2,2,37)
insert into lines (line, stopid, boardings)
values (2,3,40)
insert into lines (line, stopid, boardings)
values (2,4,41)
insert into lines (line, stopid, boardings)
values (4,1,13)
insert into lines (line, stopid, boardings)
values (4,2,21)
insert into lines (line, stopid, boardings)
values (4,3,25)
insert into lines (line, stopid, boardings)
values (4,4,20)
insert into lines (line, stopid, boardings)
values (4,5,12)
insert into lines (line, stopid, boardings)
values (4,6,9)
insert into lines (line, stopid, boardings)
values (4,7,4)
insert into lines (line, stopid, boardings)
values (4,8,3)
insert into lines (line, stopid, boardings)
values (4,9,1)
--------------------------------------
so when I select line 2, there would be four columns, each with the boardings number in it, when I select line 4, there would be nine columns.
Thanks in advance for any help given!!
-Martin
March 26, 2013 at 11:22 am
Is there a particular reason you want to avoid the pivot function, even dynamically?
March 26, 2013 at 11:24 am
so when I select line 2, there would be four columns, each with the boardings number in it, when I select line 4, there would be nine columns.
Each row has a different number of columns? As long as you're only ever selecting one row at a time, this is a relatively simple piece of dynamic SQL and it doesn't have anything much to do with pivoting/cross-tabbing, which is converting multiple rows into multiple columns. You're generating multiple columns from a single row.
What's your sample output for a given row? What are the columns called?
March 26, 2013 at 11:31 am
thanks for the replies.
erin,
the reason i need to avoid th pivot function is because i'm using an older version that doesn't have it.
howard,
the name of the columns should be the value in [stopid]
a sample output when line 2 is chosen would be:
line1234
258374041
thanks again!!
March 26, 2013 at 12:46 pm
Sorry, I misunderstood. When you said line, I thought you meant a row of data, rather than a Line ID in your data. You need to use dynamic SQL plus either PIVOT or a "Crosstab" solution using case statements. Have a look at Jeff Moden's article on the subject:
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply