如何在一个显示中合并Sql两个sql查询结果显示合并

时间:2017-04-10 14:35:03

标签: sql-server merge

我想在一个屏幕上并排合并sql查询结果

示例:

Barcode1    Barcode2
888            33

有可能吗?

非常感谢你。

SELECT BARCODE AS BARCODE2  
FROM LG_001_UNITBARCODE, LG_001_ITEMS
WHERE ITEMREF = LG_001_ITEMS.LOGICALREF 
  AND ITEMREF= 17 AND LINENR = 2;


SELECT BARCODE AS BARCODE3 
FROM LG_001_UNITBARCODE, LG_001_ITEMS 
WHERE ITEMREF = LG_001_ITEMS.LOGICALREF 
  AND ITEMREF= 17 AND LINENR = 3;

enter image description here

2 个答案:

答案 0 :(得分:0)

一种方法是使用如下的子选择:

SELECT BARCODE AS BARCODE2 ,
        (
            SELECT BARCODE AS BARCODE3 
            FROM LG_001_UNITBARCODE, LG_001_ITEMS 
            WHERE ITEMREF = LG_001_ITEMS.LOGICALREF 
                AND ITEMREF= 17 AND LINENR = 3
        ) as BARCODE3
FROM LG_001_UNITBARCODE, LG_001_ITEMS
WHERE ITEMREF = LG_001_ITEMS.LOGICALREF 
AND ITEMREF= 17 AND LINENR = 2;

答案 1 :(得分:0)

如果我们可以假设如果存在多行并且每个表的结果数量不同(一个返回3个记录,另外5个)并且它们应该与每个表的条形码顺序相关... 我们可以使用2个公用表表达式和一个row_number()分析。这样,如果确实存在多行,那么它们都是基于分配的行号相关的,如果一个结果集的行数多于另一个,则会出现空值。

然而,如果它是1-1,那么这仍然有用。

WITH A as (SELECT BARCODE AS BARCODE2, row_number() over (order by barcode) RN 
           FROM LG_001_UNITBARCODE, LG_001_ITEMS
           WHERE ITEMREF = LG_001_ITEMS.LOGICALREF 
             AND ITEMREF= 17 
             AND LINENR = 2),
     B as (SELECT BARCODE AS BARCODE3, row_number() over (order by barcode) RN 
           FROM LG_001_UNITBARCODE, LG_001_ITEMS 
           WHERE ITEMREF = LG_001_ITEMS.LOGICALREF 
             AND ITEMREF= 17 
             AND LINENR = 3)

SELECT A.Barcode2, B.Barcode3 
FROM A
FULL OUTER JOIN B 
 on A.RN = B.RN
;

Row_number()RN为我们提供了一种将条形码asc序列中的表关联起来的方法。如果一个数据集的记录多于另一个数据集,则完整的外部联接允许我们处理。