从sql server中的两个表中检索数据

时间:2016-12-26 11:43:07

标签: sql sql-server tsql select

我有两个表,我必须从两个表中检索数据而没有重复的行。

有表(a)

BILL_DATE   BILL_AMOUNT       
----------
20160208    94  
20160208    140     
20160208    30  
20160208    25  
20160208    14  
20160208    6   
20160208    35  
20160208    20  
20160208    35  

=======================

第二个表是(b)

enter image description here

我希望得到像

的结果

enter image description here

3 个答案:

答案 0 :(得分:1)

您可以在日期使用完整的外部联接,以便从任何一张表中获取相关的行:

SELECT          COALESCE(bill_date, reach_date) AS [date], 
                bill_date, bill_amount, 
                reach_date AS [recharge_date], reach_amount AS [recharge_amount]
FROM            a
FULL OUTER JOIN b on a.bill_date = b.reach_date

答案 1 :(得分:0)

试试这个:

SELECT ISNULL(X.BILL_DATE,X.RECHARGE_DATE) AS DATE,X.*
FROM (
       SELECT BILL_DATE,BILL_AMOUNT as BILL_AMT,null as RECHARGE_DATE,null as RECHARGE_AMT
       FROM Tablea
       UNION ALL
       SELECT null as BILL_DATE,null as BILL_AMT,RECH_DATE as RECHARGE_DATE,RECH_AMOUNT as RECHARGE_AMT                                                                        
       FROM Tableb
       ) X

答案 2 :(得分:0)

问题不明确,但如果你想要13行

select bill_date as "DATE", bill_date, bill_amount, null as "recharge_date" , null as "recharge_amount" 
from a
union all
select rech_date          , null     , null       , rech_date               , rech_amount              
from b;

不清楚如何获得100,200,300,400的rech_amount