从具有相同行数的联合选择表中加入2个别名表

时间:2018-10-19 06:10:08

标签: postgresql

我从select和union的别名表结果中拥有2个表,并且具有相同的行数,如何或如何在表1的右侧制作表2?没有相同的记录 谢谢

第一个查询:

SELECT * FROM (
    SELECT COUNT(*) “DATA 220” FROM istros_sls_store.sales_store_220)—CEK
    UNION ALL
    SELECT COUNT(*) FROM istros_sls_item_sales_item_220)—CEK
    UNION ALL
    SELECT COUNT(*) FROM istros_sls_scat_sales_small_cat_220—CEK
    UNION ALL
    SELECT COUNT(*) FROM istros_inventory_hstr.inventory_hstr_dtl_220)—CEK
    UNION ALL
    SELECT COUNT(*) FROM istros_sos.stock_out_supplier_220—CEK
) a

第一个查询的输出:

DATA 220
41
236633
11509
187174
1132

第二个查询:

SELECT * FROM (
    SELECT COUNT(*) “DATA 226” FROM istros_sls_store.sales_store_226—CEK
    UNION ALL
    SELECT COUNT(*) FROM istros_sls_item_sales_item_226—CEK
    UNION ALL
    SELECT COUNT(*) FROM istros_sls_scat_sales_small_cat_226—CEK
    UNION ALL
    SELECT COUNT(*) FROM istros_inventory_hstr.inventory_hstr_dtl_226—CEK
    UNION ALL
    SELECT COUNT(*) FROM istros_sos.stock_out_supplier_226—CEK
) b

第二个查询的输出:

DATA 226
41
243053
11437
193549
960

所需的输出结合了这两列:

DATA 220 | DATA 226
41       | 41
236633   | 243053
11509    | 11437
187174   | 193549
1132     | 960

1 个答案:

答案 0 :(得分:0)

您可以尝试在联合查询中选择两个计数,以便每个计数在输出中显示为单独的列。请注意,下面我介绍了一个计算列pos,该列用于跟踪哪些计数查询应首先出现在结果集中。

SELECT "DATA 220", "DATA 226"
FROM
(
    SELECT
        1 AS pos,
        (SELECT COUNT(*) FROM istros_sls_store.sales_store_220) AS “DATA 220”,
        (SELECT COUNT(*) FROM istros_sls_store.sales_store_226) AS “DATA 226”
    UNION ALL
    SELECT
        2,
        (SELECT COUNT(*) FROM istros_sls_item_sales_item_220),
        (SELECT COUNT(*) FROM istros_sls_item_sales_item_226)
    UNION ALL
    SELECT
        3,
        (SELECT COUNT(*) FROM istros_sls_scat_sales_small_cat_220),
        (SELECT COUNT(*) FROM istros_sls_scat_sales_small_cat_226)
    UNION ALL
    SELECT
        4,
        (SELECT COUNT(*) FROM istros_inventory_hstr.inventory_hstr_dtl_220),
        (SELECT COUNT(*) FROM istros_inventory_hstr.inventory_hstr_dtl_226)
    UNION ALL
    SELECT
        5,
        (SELECT COUNT(*) FROM istros_sos.stock_out_supplier_220),
        (SELECT COUNT(*) FROM istros_sos.stock_out_supplier_226)
) t
ORDER BY
    pos;