LoginSignup
17
15

More than 5 years have passed since last update.

PostgreSQLでは副問い合わせ(subquery)に別名を付けないと怒られたメモ

Last updated at Posted at 2016-06-30

怒られたSQL文


SELECT
    年月,
    SUM(販売金額) AS 販売合計金額
FROM
    (
        SELECT
            TO_CHAR(s.sale_date, 'yyyy-mm') AS 年月,
            s.quantity * p.price AS 販売金額
        FROM
            sales AS s
                JOIN
            products AS p ON  s.product_id = p.product_id
    )
GROUP BY
    年月
ORDER BY
    年月
;

----------------------------------------------------
db_name=# 上記SQL文
ERROR:  subquery in FROM must have an alias
LINE 1: select 年月, sum(販売金額) as 販売合計金額 from (select TO_C...
                                                        ^
HINT:  For example, FROM (SELECT ...) [AS] foo.

修正したSQL文


SELECT
    年月,
    SUM(販売金額) AS 販売合計金額
FROM
    (
        SELECT
            TO_CHAR(s.sale_date, 'yyyy-mm') AS 年月,
            s.quantity * p.price AS 販売金額
        FROM
            sales AS s
                JOIN
            products AS p ON  s.product_id = p.product_id
    ) AS 販売実績別合計金額 !!!!ココ!!!!
GROUP BY
    年月
ORDER BY
    年月
;

補足:そもそも副問い合わせを使わないSQL文


SELECT
    TO_CHAR(s.sale_date, 'yyyy-mm') AS 年月,
    SUM(s.quantity * p.price) AS 合計販売金額
FROM
    sales AS s
        JOIN
    products AS p ON  s.product_id = p.product_id
GROUP BY
    TO_CHAR(s.sale_date, 'yyyy-mm')
ORDER BY
    TO_CHAR(s.sale_date, 'yyyy-mm')
;
17
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
15