并排列合并

问题描述

我需要创建一个价格比较工具,所以出现了这样的要求。为此,我的数据库查询有两个不同的结果集。我的数据库sql Server 2017 开发版。我想要的是并排合并两个结果集。见下图:

enter image description here

我的查询

SELECT ADuration Duration,APlan_Price AmazonPrice 
FROM tbl_AmazonPlans
WHERE AProduct_Name = 'Air Conditioner'
  AND 14678 BETWEEN TRY_CONVERT(int,PARSENAME(REPLACE(APrice_Range,'-','.'),2))
                AND TRY_CONVERT(int,1))

SELECT Duration,Plan_Price GwPrice
FROM tbl_PlanDetails
WHERE Product_Name = 'Air Conditioner'
  AND 14678 BETWEEN TRY_CONVERT(int,PARSENAME(REPLACE(Price_Range,1))

更新

来自表的结果集可能/可能不具有相同的架构。也没有连接点,因为它们没有公共键。但是是的,它们包含的列可能相同,并且基于这些相同的列,我必须获得预期的结果集。

解决方法

您可以直接加入表格,但如果您的 where 条件可能不同以保持简单,您可以直接加入结果集

select a.duration,a.AmazonPrice,b.GwPrice
from (
    Select ADuration Duration,APlan_Price AmazonPrice 
    From tbl_AmazonPlans
    Where AProduct_Name ='Air Conditioner'
    and 14678 between try_convert(int,parsename(replace(APrice_Range,'-','.'),2))
                                and try_convert(int,1))
)a
join
(
    Select Duration,Plan_Price GwPrice
     From tbl_PlanDetails
     Where Product_Name ='Air Conditioner'
    and 14678 between try_convert(int,parsename(replace(Price_Range,1))
)b on a.duration = b.duration
,

Duration 列是两个表中通用的标识符吗?如果是,那么您可以使用内连接。

select
    Duration,APlan_Price as AmazonPrice
    Plan_Price as GwPrice
from tbl_AmazonPlans
inner join tbl_PlanDetails on tbl_PlanDetails.Duration = tbl_AmazonPlans.Duration
where /* Your filter here */