Concat/Union SQL 中的两个表

Concat/Union two tables in SQL

下面的 sql 查询创建了两个表,tab1 有 3 列(quarter、region 和 datasum),tab2 有 2 列(quarter 和 datasum)。

我想将 tab1 和 tab2 的值堆叠在一起(就像 pandas/python 中的 pd.concat([tab1, tab2]) 一样。为此,我需要在 tab2 中创建一个名为 region 的新列,并将其插入与 tab1 中相应列相同的位置。之后我想我需要使用 UNION_ALL.

在 tab2 中,我希望每个实例的列区域的值都是 'all'。

我怎样才能做到这一点?

我尝试使用 ALTER TABLE 和 ADD,但我不觉得它对我有用。帮助将不胜感激。 我在 SQL Oracle 工作。

with base1 as(
    select substr(municip,1,2) as region, data, age,
            case when substr(time,6,2) in ('01','02','03') then substr(time, 1,4) || '_1'
                                when substr(time,6,2) in ('04','05','06') then substr(time, 1,4) || '_2'
                                when substr(time,6,2) in ('07','08','09') then substr(time, 1,4) || '_3' 
                                else substr(time, 1,4) || '_4' end quarter
        
                from sql_v1
                where time >= '2021-01' and
                ),
                  
base2 as(select data, age,
            case when substr(time,6,2) in ('01','02','03') then substr(time, 1,4) || '_1'
                                when substr(time,6,2) in ('04','05','06') then substr(time, 1,4) || '_2'
                                when substr(time,6,2) in ('07','08','09') then substr(time, 1,4) || '_3' 
                                else substr(time, 1,4) || '_4' end quarter 
                from sql_v1
                where time >= '2021-01'),       

tab1 as (select quarter, region,
    sum (case when age between '16' and '64' then kvar else 0 end) datasum 
    from base
    group by quarter, region
    order by quarter, region),
    
tab2 as (select quarter,
    sum (case when age between '16' and '64' then kvar else 0 end) datasum 
    from riket
    group by quarter
    order by quarter)

...select * from tab_union

您似乎在使用字符串来存储日期???不要那样做:(

如果您使用本机日期时间数据类型,那么您可以使用 TO_CHAR(datetime_column, 'Q')

之类的方法提取季度

但是现在,使用可怕的数据类型,您可以重组查询以在 GROUP BY...

中使用 ROLLUP
WITH
  formatted AS
(
  SELECT
    SUBSTR(municip,1,2)                                                                 AS region,
    SUBSTR(time, 1,4) || CASE WHEN SUBSTR(time,6,2) IN ('01','02','03') THEN '_1'
                              WHEN SUBSTR(time,6,2) IN ('04','05','06') THEN '_2'
                              WHEN SUBSTR(time,6,2) IN ('07','08','09') THEN '_3' 
                                                                        ELSE '_4' END   AS quarter,
    age,
    kvar
  FROM
    sql_v1
  WHERE
    time >= '2021-01'
)
SELECT
  region,
  COALESCE(quarter, 'All'),
  SUM(CASE WHEN age BETWEEN 16 AND 64 THEN kvar ELSE 0 END)
FROM
  formatted
GROUP BY
  region, ROLLUP(quarter)
ORDER BY
  region,
  GROUPING(quarter),
  quarter

演示:https://dbfiddle.uk/?rdbms=oracle_21&fiddle=ab27d71ac81bb9bc7e5e06e7f5a44ba9

或者,使用 DATE 数据类型:https://dbfiddle.uk/?rdbms=oracle_21&fiddle=1544406dc2b6669bc62ed02a6155b1c2