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 |
|
GustiX
Starting Member
28 Posts |
Posted - 2010-07-28 : 11:55:04
|
| HiI have a query that I would like to simplify.It is basiclyselect a, b, c, (select x from sometable ....) as x, (select y from sometable ....) as yfrom sometable Since the subqueries are pretty long and complicated and are the same for x and y I would like to be able to do something like thisselect a, b, c, (select x,y from sometable ....) as x,yfrom sometableThis, of course, gives me an error. Is there any neat way ofachieving this? |
|
|
Sachin.Nand
2937 Posts |
Posted - 2010-07-28 : 13:20:28
|
| Is there any relationship between tables x & y?Please post some sample data & expected o/p.Limitations live only in our minds. But if we use our imaginations, our possibilities become limitless. PBUH |
 |
|
|
GustiX
Starting Member
28 Posts |
Posted - 2010-07-28 : 17:30:49
|
| x and y are fields not tableslets say we have 2 tablescustomer -customer_id -nameandaddress -customer_id -street -city -created_datethen we create a queryselect customer_id, name, (select top 1 street from address where customer_id = c.customer_id order by created_date), (select top 1 city from address where customer_id = c.customerid order by created_date)from customer cwhat I would like to be able to do isselect customer_id, name, (select top 1 street, city from address where customer_id = c.customer_id order by created_date)from customer c |
 |
|
|
PavanKK
Starting Member
32 Posts |
Posted - 2010-07-29 : 03:22:23
|
| try this...;WITH cte AS( SELECT customer_id ,street ,city ,ROW_NUMBER()OVER(PARTITION BY customer_id ORDER BY created_date) AS Rno FROM address)SELECT C.customer_id ,C.name ,CT.street ,CT.cityFROM customer cLEFT JOIN cte CT ON C.ProductModelID = CT.ProductModelID AND CT.Rno = 1KK :) |
 |
|
|
Sachin.Nand
2937 Posts |
Posted - 2010-07-29 : 04:24:10
|
| [code]selectc.customer_id,c.name,T.street,T.city from customer cCross Apply ( select top 1 street, city from address where customer_id = c.customer_id order by created_date )T[/code]Limitations live only in our minds. But if we use our imaginations, our possibilities become limitless. PBUH |
 |
|
|
|
|
|
|
|