| Author |
Topic |
|
quantoidboy
Starting Member
1 Post |
Posted - 2008-06-06 : 19:33:42
|
| This is kind of tricky. I have a table that is structured like this (where the StaffID is the primary key):StaffID, Date1, Amount1, Date2, Amount2, Date3, Amount3123, 1/1/08, 100, 2/1/08, 200, 3/1/08, 300You can already see that whoever made this table wasn't thinking prudently. Anyway, I would like to make the table look like this:StaffID, Date, Amount123, 1/1/08, 100123 2/1/08, 200123 3/1/08, 300Where the StaffID and Date are concatenated keys.Is there a way to either create a View or create a Query Table that converts the data like that for me? I need the new view/query to update when the original table updates, so a new table isn't an option.Thanks ahead of time!Reuben |
|
|
ranganath
Posting Yak Master
209 Posts |
Posted - 2008-06-07 : 03:11:29
|
| Hi,try with this DEclare @T Table ( StaffID Int, Date1 varchar(100), Amount1 Int, Date2 varchar(100), Amount2 Int, Date3 varchar(100), Amount3 Int )Insert into @TSelect 123, '1/1/08', 100, '2/1/08', 200, '3/1/08', 300 union allSelect 124, '1/1/08', 1000, '2/1/08', 2000, '3/1/08', 3000 Select Staffid, Date1 + ' - ' + CAST(Amount1 as varchar(100)) +'#'+ Date2 + ' - ' + CAST(Amount2 as varchar(100))+'#'+ Date3 + ' - ' + CAST(Amount3 as varchar(100)) as 'Data' into #T From @T DECLARE @delimiter NVARCHAR(5)SELECT @delimiter = '#'Declare @Temp Table ( id int, Val varchar(100))insert into @TempSELECT s.Staffid, SUBSTRING(s.data, v.Number - 1, COALESCE(NULLIF(CHARINDEX('#', s.data, v.Number), 0), LEN(s.data) + 1) - v.Number + 1) AS valueFROM #T AS sINNER JOIN master..spt_values AS v ON v.Type = 'p'WHERE SUBSTRING('#_' + s.data, v.Number, 1) = '#'Select id, Substring(Val,1,charindex ('-', val)-1) as Date, Substring(Val,9,len(val)) as Amount From @Tempdrop table #T |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-06-07 : 04:10:29
|
or even thisSELECT StaffID,Date1 AS Date,Amount1 AS AmountFROM TableUNION ALLSELECT StaffID,Date2,Amount2FROM TableUNION ALLSELECT StaffID,Date3,Amount3FROM Table |
 |
|
|
|
|
|