【问题标题】:Trouble COUNT function in INSERT statement [duplicate]INSERT 语句中的故障 COUNT 函数[重复]
【发布时间】:2022-01-05 22:29:54
【问题描述】:

我正在尝试将数据插入表中,但在使用 COUNT 函数时遇到了问题。 count_rentals 和 count_returns 列应该代表给定电影被租借和归还的次数。

我尝试将数据插入表中的数据集 (sakila) 没有计算出租金和退货的数量,而是有一个 return_date 和 rent_date 列。我想在这两列上使用 COUNT 会给我电影被租借和归还的次数(因为租借日期会出现在租借日期中,归还日期会出现在归还日期中),所以我是这样写的:

INSERT INTO sakila_snowflake.fact_rental (
    rental_id,
    rental_last_update,
    customer_key,
    staff_key,
    film_key,
    store_key,
    rental_date_key,
    return_date_key,
    count_returns,
    count_rentals,
    rental_duration,
    dollar_amount)
    (SELECT
    s_rental.rental_id,
    s_rental.last_update,
    s_customer.customer_id,
    s_staff.staff_id,
    s_film.film_id,
    s_store.store_id,
    s_rental.rental_date,
    s_rental.return_date,
    Count(s_rental.rental_date),
    Count(s_rental.return_date),
    s_rental.return_date - s_rental.rental_date,
    (s_rental.return_date - s_rental.rental_date)*s_film.rental_rate
    FROM
    sakila.rental as s_rental,
    sakila.customer as s_customer,
    sakila.staff as s_staff,
    sakila.film as s_film,
    sakila.store as s_store
    WHERE
    s_rental.staff_id = s_staff.staff_id AND s_staff.store_id=s_store.store_id AND s_store.store_id = s_customer.store_id);

但是,当我尝试运行它时,我得到了这个错误:

错误代码:1140。在没有 GROUP BY 的聚合查询中,表达式 #1 的 SELECT 列表包含非聚合列 'sakila.s_rental.rental_id';这与 sql_mode=only_full_group_by。

我不太确定如何在不使用 COUNT 函数的情况下获取 count_rental 和 count_return 列的电影被租借和返回的次数。如果有人有任何建议,我将非常感激:)

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    如果您想要计数但不想分组,则需要执行窗口功能。如果您对电影的计数感兴趣,那将是

    count(s_rental.rental_date) over (partition by s_film.film.id)
    

    https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html

    【讨论】:

    • 还有比这更多的错误;看起来他们希望每次租借插入一张唱片,但正在交叉加入电影,也许还有客户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多