Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Arithmomaniac
Yak Posting Veteran
66 Posts |
Posted - 2008-07-02 : 12:21:59
|
| let's say I have a table that looks like this:[font=Andale Mono]Product | Time | Number___________________________Bikes | 9:00 | 3Bikes | 9:30 | 4Tires | 10:00 | 7Bikes | 10:00 | 1Tires | 10:30 | 2If I used (SELECT DISTINCT Bikes, Min(Time), Sum(Number)), I'd haveBikes | 9:00 | 8But what If I wanted the Number for the first Time in a product in the forth colums, like the following?Bikes | 9:00 | 8 | 3Tires | 10:00 | 9 | 7Is there any good way to do that? All that comes to mind is an ugly self-referential join.Thanks,Arithmomaniac---------Ignorance may be bliss, but knowledge is thrill. |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2008-07-02 : 12:49:12
|
| select t1.* from table t1 inner join (select product,min(time) as time from table group by product) as t2on t1.Product =t2.product and t1.Time=t2.timeMadhivananFailing to plan is Planning to fail |
 |
|
|
Arithmomaniac
Yak Posting Veteran
66 Posts |
Posted - 2008-07-02 : 13:34:19
|
quote: Originally posted by madhivanan select t1.* from table t1 inner join (select product,min(time) as time from table group by product) as t2on t1.Product =t2.product and t1.Time=t2.time
That leaves Bikes | 9:00 | 3. How do I get the 8 back in? None of the other rows are even in the source table, as they were eliminated in the join.I thought about it more after posting, and I guess you have to do taht join. I think the best approach would be to make the | 3 | term a nested subquery:SELECT Product, Min(Time) AS FirstTime, Sum(Number) AS Sum,(SELECT Number FROM Table AS Table2 WHERE Table2.Time = Table1.FirstTime AS FirstSale)FROM Table AS Table1 ---------Ignorance may be bliss, but knowledge is thrill. |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2008-07-02 : 13:41:24
|
| select t1.*,t2.number from table t1 inner join (select product,min(time) as time,sum(number) as number from table group by product) as t2on t1.Product =t2.product and t1.Time=t2.timeMadhivananFailing to plan is Planning to fail |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-07-02 : 13:47:16
|
| [code]SELECT t.Product, MIN(Time), SUM(Number), MAX(CASE WHEN RowNo=1 THEN Number ELSE NULL END) AS First FROM(SELECT ROW_NUMBER() OVER(PARTITION BY Product ORDER BY Time) AS RowNo,*FROM Table)tGROUP BY Product[/code] |
 |
|
|
|
|
|
|
|