SQL: 如何从不同的表中添加不同的列并使其成为一个数量?

SQL: How do I add different columns from different tables and make it one amount?

我正在尝试从不同的表中添加列以获得我所有流的总量。我试过加入 SQL JOIN 它们,效果很好,但它不允许我获得流的总数。我现在决定使用 union SQL UNION all 但我仍然无法获得流的总数。在连接这些表格后,我如何着手获得最终金额。我从之前关于堆栈溢出的问题中得到的解决方案似乎也不起作用。

from http.client import OK
from logging import exception
import psycopg
import pandas as pd

dbname = '******' 
user ='******'
password = '*******' 
host = '**********' 
port = **** 
conn = None

try:
    with psycopg.connect(
        dbname = dbname,
        user = user,
        password = password,
        host = host, 
        port = port 
    ) as conn:

        with conn.cursor() as cur:

            total_streaming_plays = '''SELECT artist, SUM(plays) AS total_plays
            FROM SELECT artist, plays FROM machine_spotify
            UNION ALL
            SELECT artist, plays FROM machine_tidal
            UNION ALL
            SELECT artist, plays FROM machine_soundcloud
            UNION ALL
            SELECT artist, plays FROM machine_youtube
            UNION ALL
            SELECT artist, plays FROM machine_youtube_music
            GROUP BY artist;'''

            cur.execute(total_streaming_plays) 
            for records in cur:
                print(records)   

        conn.commit()

except Exception as e:
    print(e)

finally:
    if conn is not None:
        conn.close()

输出

syntax error at or near "SELECT"
LINE 2:             FROM SELECT artist, plays FROM machine_spotify

我想你需要一个()

SELECT artist, SUM(plays) AS total_plays
            FROM (SELECT artist, plays FROM machine_spotify)
            UNION ALL
            (SELECT artist, plays FROM machine_tidal)
            UNION ALL
            (SELECT artist, plays FROM machine_soundcloud)
            UNION ALL
            (SELECT artist, plays FROM machine_youtube)
            UNION ALL
            (SELECT artist, plays FROM machine_youtube_music)
            GROUP BY artist;

我认为这会解决错误,但我认为这不是一个好的做法,我更愿意使用 With AS

WITH temp AS (
    SELECT artist, plays FROM machine_spotify
            UNION ALL
            (SELECT artist, plays FROM machine_tidal)
            UNION ALL
            (SELECT artist, plays FROM machine_soundcloud)
            UNION ALL
            (SELECT artist, plays FROM machine_youtube)
            UNION ALL
            (SELECT artist, plays FROM machine_youtube_music)
)
SELECT artist, SUM(plays) AS total_plays
FROM temp

总而言之,没有样本数据很难给出建议。