SQL并排获取两个不同的行

时间:2017-06-07 21:54:00

标签: sql sql-server

我从SQL查询中获取此结果集:

TypeID  Address   CityID    Zip          isPreferred
----------------------------------------------------
  1     SA-09     17986     897464654         0
  2     FF-31     17987     564646656         0

SQL查询是

SELECT 
    rAdrs.ContactTypeID, rAdrs.StreetAddress, 
    rAdrs.CityID, rAdrs.Zip,  rAdrs.isPreferred 
FROM 
    [Address] AS rAdrs  
WHERE
    rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1

UNION

SELECT 
    mAdrs.ContactTypeID, mAdrs.StreetAddress, 
    mAdrs.CityID, mAdrs.Zip,  mAdrs.isPreferred 
FROM 
    [Address] AS mAdrs  
WHERE 
    mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2

但我想要的结果是这种格式:

TypeID  Address  CityID   Zip       TypeID    Address   CityID   Zip        Preferred
----------------------------------------------------------------------------------------
  1     SA-09    17986    897464654   2       FF-31     17987    564646656  2

2 个答案:

答案 0 :(得分:0)

使用CROSS APPLY

select a.*,b.*
from (
SELECT 
rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip,  rAdrs.isPreferred 
FROM [Address] AS rAdrs  
WHERE rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1
) a
cross apply 
(
SELECT 
mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip,  mAdrs.isPreferred 
FROM [Address] AS mAdrs  
WHERE mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
) b

演示

declare @t1 table(id smallint,str char(2))
insert into @t1 values (1,'aa')

declare @t2 table(id smallint,str char(2))
insert into @t2 values (2,'bb')


select a.*,b.*
from 
(select * from @t1) a
cross apply
(select * from @t2) b

select a.*,b.*
from @t1 a
cross apply
(
select * from @t2
) b

结果

id  str id  str
1   aa  2   bb

答案 1 :(得分:0)

A(隐式CROSS)JOIN也在这里工作:

SELECT rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip, rAdrs.isPreferred,
       mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip, mAdrs.isPreferred
  FROM [Address] AS rAdrs  
  JOIN [Address] AS mAdrs on mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
 WHERE rAdrs.Applicantid = 5
   AND rAdrs.ContactTypeID = 1

或明确的:

SELECT rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip, rAdrs.isPreferred,
       mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip, mAdrs.isPreferred
  FROM [Address] AS rAdrs  
 CROSS JOIN [Address] AS mAdrs
 WHERE rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1
   AND mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2