| Author |
Topic |
|
Esturk
Starting Member
1 Post |
Posted - 2010-01-02 : 19:56:01
|
| I got 2 tables:Item / Desc1 / One2 / Two3 / Three&Item / Month / Sold1 / 5 / 101 / 6 / 112 / 5 / 202 / 6 / 213 / 5 / 303 / 6 / 31Trying to figure out a select statement that will display the following:Item / Desc / Month_5 / Month_61 / One / 10 / 112 / Two / 20 / 213 / Three / 30 / 31Any help would be appreciated.Esturk |
|
|
ddramireddy
Yak Posting Veteran
81 Posts |
Posted - 2010-01-02 : 22:48:38
|
| select Item,[Desc],[5] as Month_5,[6] as Month_6 from ( select I.Item,I.[Desc],ISo.[Month],ISo.[Sold] from Items I inner join ItemSold ISo on I.Item = ISo.Item)ppivot (max([Sold]) for [MOnth] in ([5],[6]))pvtand also please look at pivot in Books Online... |
 |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2010-01-02 : 22:57:56
|
| [code]Declare @temp table(item int, [Desc] varchar(10))Insert @tempSelect 1,'One' union allSelect 2,'Two' union allSelect 3,'Three'Declare @tmp table( item int, [Month] int, Sold int)Insert @tmpSelect 1,5,10 union allSelect 1 ,6 ,11 union allSelect 2 , 5 , 20 union allSelect 2 , 6 ,21 union allSelect 3 , 5 , 30 union allSelect 3 , 6 , 31 Select p.item,[Desc],Max(Case When P.Seq = 1 then Sold Else Null End) [Month_5],Max(Case When P.Seq = 2 then Sold Else Null End) [Month_6]--Max(Case ..Seq = 3 then ...End),....from(Select tp.item,[Desc],Sold,ROW_Number() Over(Partition by tp.item,[Desc] Order by tp.item)as seqfrom @temp tpinner join @tmp tmp on tp.item = tmp.item)PGroup by P.item,[Desc]Order by P.itemOr Simply(If you are looking for Max and Min)Select tp.item,[Desc],Min(Sold),Max(Sold)from @temp tpinner join @tmp tmp on tp.item = tmp.item[/code] |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2010-01-03 : 00:55:38
|
just small modificationquote: Originally posted by sodeep
Declare @temp table(item int, [Desc] varchar(10))Insert @tempSelect 1,'One' union allSelect 2,'Two' union allSelect 3,'Three'Declare @tmp table( item int, [Month] int, Sold int)Insert @tmpSelect 1,5,10 union allSelect 1 ,6 ,11 union allSelect 2 , 5 , 20 union allSelect 2 , 6 ,21 union allSelect 3 , 5 , 30 union allSelect 3 , 6 , 31 Select p.item,[Desc],Max(Case When P.Seq = 1 then Sold Else Null End) [Month_5],Max(Case When P.Seq = 2 then Sold Else Null End) [Month_6]--Max(Case ..Seq = 3 then ...End),....from(Select tp.item,[Desc],Sold,ROW_Number() Over(Partition by tp.item,[Desc] Order by tp.item)as seqfrom @temp tpinner join @tmp tmp on tp.item = tmp.item)PGroup by P.item,[Desc]Order by P.itemOr Simply(If you are looking for Max and Min)Select tp.item,[Desc],Min(Sold),Max(Sold)from @temp tpinner join @tmp tmp on tp.item = tmp.item Group by P.item,[Desc]
|
 |
|
|
|
|
|