从两个表中选择一个表

时间:2016-12-14 19:12:54

标签: sql-server

我不知道是否可能。如果可能,请帮我解决这个问题。

我有两张桌子, table1 table2

Table1                                     Table2

CashReceivedFrom     Amount               CashPaidOutto      Amount        
x                    100                   A                     300   
Y                    200                   B                     400 
z                    250 
xy                   300  

table1和table2之间没有关系。我想执行一个查询,以便我的输出如下所示:

输出表格

CashReceivedFrom     Amount               CashPaidOutto      Amount        
    x                    100                   A               300   
    Y                    200                   B               400 
    z                    250 
    xy                   300

我想将它用于每日现金报销

2 个答案:

答案 0 :(得分:0)

请尝试以下声明。我不知道为什么你需要Null的数据。但是下面的代码片段可能对你有帮助。

   SELECT * FROM (
  SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) 
  AS SNO, CASHRECIEVEDFROM, AMOUNT FROM TABLE1
  ) AS A
  FULL OUTER JOIN
   SELECT * FROM (
  SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) 
  AS SNO, CASHPAIDTO, AMOUNT FROM TABLE2
  ) AS B ON A.SNO = B.SNO

答案 1 :(得分:0)

这可以满足您的需求。

CREATE TABLE #TMP1 (ID INT,Amnt INT)
CREATE TABLE #TMP2 (ID INT,Amnt INT)

INSERT INTO #TMP1 VALUES
(1,100)
,(2,130)
,(3,10)
,(4,160)

INSERT INTO #TMP2 VALUES
(76,1024)
,(78,134)

;WITH cteA
    AS
    (
    SELECT *
        ,ROW_NUMBER() OVER(ORDER BY ID) AS Pos
    FROM #TMP1
    )
,cteB
    AS
    (
    SELECT *
        ,ROW_NUMBER() OVER(ORDER BY ID) AS Pos
    FROM #TMP2
    )
SELECT
    A.ID
    ,A.Amnt
    ,B.ID
    ,B.Amnt
FROM
    cteA A
        LEFT JOIN cteB  B
            ON
            A.Pos = B.Pos