通过减少重复列名称的冗余来清除SQL语句

时间:2017-11-19 01:10:45

标签: sql postgresql

我发现自己重复在SQL语句中的各个部分写入列名。下面是一个例子,我需要帮助看看是否有更好的写作方式。正在重复列表列表,首先是在GROUP BY子句中,其次是在UNION期间的SELECT中。

来自编程背景,我认为这可以在某处定义为模板,并重复使用。如果有人可以帮我指出正确的方法,我会去手册。

我只在这里显示两个表的UNION,但实际上我必须为大约10个公司报告做UNION。我目前正在使用Postgres 10。

CREATE MATERIALIZED VIEW staging.journal_2017_total AS
(
    WITH 
    company_1 AS (
        SELECT 'COMPANY 1' AS source, year, month_no, year_month, profit_center, revenue_class,
               cust_acc_name, billing_acc_name, sum(amount) AS amount
        FROM staging.journal_company_1
        GROUP BY year, month_no, year_month, profit_center, revenue_class,
               cust_acc_name, billing_acc_name
    ),

    company_2 AS (
        SELECT 'COMPANY 2' as source, year, month_no, year_month, profit_center, revenue_class,
               cust_acc_name, billing_acc_name, sum(amount) AS amount
        FROM staging.journal_company_2
        GROUP BY year, month_no, year_month, profit_center, revenue_class,
               cust_acc_name, billing_acc_name
    )

    SELECT source, year, month_no, year_month, profit_center, revenue_class,
               cust_acc_name, billing_acc_name, amount
    FROM company_1

    UNION ALL

    SELECT source, year, month_no, year_month, profit_center, revenue_class,
               cust_acc_name, billing_acc_name, amount
    FROM company_2
)

2 个答案:

答案 0 :(得分:0)

它们都是您定义的CTE,因此您可以小心确保具有相同顺序的相同列并写入:

SELECT *
FROM company_1
UNION ALL
SELECT *
FROM company_2

但是,复制和粘贴列表似乎并不过分繁琐。

答案 1 :(得分:0)

这样做会减少指定列的次数。 如果不是表中的相同列,将会中断,因此在这方面有些失败。

SELECT source, year, month_no, year_month, profit_center, revenue_class,
               cust_acc_name, billing_acc_name, sum(amount) AS amount
        FROM 
        (
          SELECT 'COMPANY 1' AS source, x.*
          FROM staging.journal_company_1 x
          union all
          SELECT 'COMPANY 2' AS source, x.*
          FROM staging.journal_company_2 x
        )
        GROUP BY source/*add this */,year, month_no, year_month, profit_center, revenue_class,cust_acc_name, billing_acc_name