My Query:
SELECT portfolio_id,
sum(shares_owned_value_usd) as sum_shares_owned_value_usd,
date_utc,
sum(dividends_received_value_usd) as total_dividends_received_usd,
(sum(dividends_received_value_usd) over (order by date_utc range between interval 1 year preceding and current row)) as dividends_usd_ttm
FROM stock_portfolio_historical_values
WHERE portfolio_id = 5
GROUP BY date_utc
ORDER BY date_utc ASC
Error:
Error Code: 1055. Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'stock_portfolio_historical_values' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
My table stock_portfolio_historical_values
has a primary key named id
, if this is needed to fix my query.
My Schema:
id | portfolio_id | ticker | shares_owned_value_usd | dividends_received_value_usd | date_utc |
---|---|---|---|---|---|
500 | 5 | AAPL | 300 | 15 | 2022-06-08 |
499 | 5 | MSFT | 1000 | 30 | 2022-06-08 |
498 | 5 | AAPL | 200 | 0 | 2022-06-07 |
497 | 5 | MSFT | 900 | 0 | 2022-06-07 |
. | . | . | . | . | . |
403 | 5 | AAPL | 300 | 15 | 2022-03-05 |
402 | 5 | MSFT | 1000 | 30 | 2022-03-05 |
. | . | . | . | . | . |
102 | 5 | AAPL | 300 | 10 | 2021-03-05 |
101 | 5 | MSFT | 1000 | 15 | 2021-03-05 |
Expected Results:
portfolio_id | sum_shares_owned_value_usd | total_dividends_received_usd | dividends_usd_ttm | date_utc |
---|---|---|---|---|
5 | 1300 | 45 | 90 | 2022-06-08 |
5 | 1100 | 0 | 45 | 2022-06-07 |
. | . | . | . | . |
. | . | . | . | . |
Note: This query works fine with ONLY_FULL_GROUP_BY
disabled, but I am trying to get it to work with it enabled.
One option is separating the aggregation from the windowing operation, then join back the two results:
WITH cte AS (
SELECT SUM(shares_owned_value_usd) AS sum_shares_owned_value_usd,
SUM(dividends_received_value_usd) AS total_dividends_received_usd,
date_utc
FROM stock_portfolio_historical_values
WHERE portfolio_id = 5
GROUP BY date_utc
)
SELECT SUM(dividends_received_value_usd) OVER(
ORDER BY date_utc
RANGE BETWEEN INTERVAL 1 YEAR PRECEDING AND CURRENT ROW) AS dividends_usd_ttm,
stock.date_utc
FROM cte
LEFT JOIN stock_portfolio_historical_values stock
AND stock.date_utc = cte.date_utc
AND stock.portfolio_id = 5
Does it work for you?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.