|
database
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Multi columns in a sub query?select Addresses.ID,
Addresses.Address1, Addresses.Address2 , Addresses.City, Addresses.State, Addresses.ZipCode, (select top 1 Phone,Email from Attributes where attAddrID=Addresses.ID), Addresses.AreaName how do I select multiple filelds in the sub query. Analyser will only let me select one or the other. I thought unless you were assigning the sub query to a @Var, you could select multiple fields in the query as long as the sub only returns one record (hense the TOP 1 statement) -- JP ..NET Software Developer You'd have to use multiple subqueries or re-write the query as a JOIN with a
derived table. For instance you could have: SELECT ... ( SELECT TOP 1 Phone FROM Attributes a1 WHERE a1.Addr_id = t1.Addr_id ORDER BY Sortcol ), ( SELECT TOP 1 Email FROM Attributes a1 WHERE a1.Addr_id = t1.Addr_id ORDER BY Sortcol ) FROM tbl t1 ; In this case you must use ORDER BY when there is a TOP clause or perhaps to get a single value, you could use a MAX() with a GROUP BY clause like: SELECT .., D.Phone, D.Email FROM tbl t1, ( SELECT Addr_id, MAX( Phone ), MAX( Email ) FROM Attributes a1 GROUP BY Addr_id ) D ( Addr_id, Phone, Email ) WHERE D.Addr_id = t1.Addr_id ; -- Anith Or
SELECT ... FROM tbl t1 WHERE Phone=( SELECT TOP 1/MAX Phone FROM Attributes a1 WHERE a1.Addr_id = t1.Addr_id ) AND/OR ----put here and /or EMAIL = ( SELECT TOP 1/MAX Email FROM Attributes a1 WHERE a1.Addr_id = t1.Addr_id ) ORDER BY Sortcol Note: It is up to you to decide(your business requirements) whether to choose TOP or MAX() Show quote "JP" <J*@discussions.microsoft.com> wrote in message news:6693B123-4B45-4449-951C-720C90CF46DF@microsoft.com... > select Addresses.ID, > Addresses.Address1, > Addresses.Address2 , > Addresses.City, > Addresses.State, > Addresses.ZipCode, > (select top 1 Phone,Email from Attributes where attAddrID=Addresses.ID), > Addresses.AreaName > > how do I select multiple filelds in the sub query. Analyser will only let me > select one or the other. I thought unless you were assigning the sub query to > a @Var, you could select multiple fields in the query as long as the sub only > returns one record (hense the TOP 1 statement) > > -- > JP > .NET Software Developer Try using the derived table in the from clause
Show quote "JP" wrote: > select Addresses.ID, > Addresses.Address1, > Addresses.Address2 , > Addresses.City, > Addresses.State, > Addresses.ZipCode, > (select top 1 Phone,Email from Attributes where attAddrID=Addresses.ID), > Addresses.AreaName > > how do I select multiple filelds in the sub query. Analyser will only let me > select one or the other. I thought unless you were assigning the sub query to > a @Var, you could select multiple fields in the query as long as the sub only > returns one record (hense the TOP 1 statement) > > -- > JP > .NET Software Developer |
|||||||||||||||||||||||