You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL查询特定工具月末价格报错:所选列需在GROUP BY子句中

获取特定Instrument的月末价格解决方案

你的原查询报错核心原因是:SQL严格模式要求SELECT中未使用聚合函数的列必须出现在GROUP BY子句中,但直接将unitPrice加入GROUP BY会导致每条日期记录单独成组,完全偏离“取每月最后一条价格”的需求。

以下是两种可行的解决方案:

方法一:使用窗口函数(推荐)

窗口函数能精准定位每个月份的最后一条记录,性能和可读性都更优:

SELECT instrumentId, unitPrice, reportedAt
FROM (
    SELECT 
        instrumentId,
        unitPrice,
        reportedAt,
        -- 按instrumentId、年份、月份分组,组内按日期降序编号
        ROW_NUMBER() OVER (
            PARTITION BY instrumentId, EXTRACT(YEAR FROM reportedAt), EXTRACT(MONTH FROM reportedAt)
            ORDER BY reportedAt DESC
        ) AS row_num
    FROM InstrumentPrice
    WHERE instrumentId = 1 -- 替换为目标instrumentId
) filtered
WHERE row_num = 1 -- 只保留每组的第一条(即当月最后一条记录)
ORDER BY reportedAt DESC;

方法二:关联子查询

通过子查询获取每个年月的最大日期,再匹配对应的价格记录:

SELECT main.instrumentId, main.unitPrice, main.reportedAt
FROM InstrumentPrice main
WHERE main.instrumentId = 1
AND main.reportedAt = (
    SELECT MAX(sub.reportedAt)
    FROM InstrumentPrice sub
    WHERE sub.instrumentId = main.instrumentId
      AND EXTRACT(YEAR FROM sub.reportedAt) = EXTRACT(YEAR FROM main.reportedAt)
      AND EXTRACT(MONTH FROM sub.reportedAt) = EXTRACT(MONTH FROM main.reportedAt)
)
ORDER BY main.reportedAt DESC;

说明

  • 两种方法都能得到你需要的结果:每个年月对应instrument的最后一条价格记录。
  • 窗口函数更适合大数据量场景,执行效率更高;关联子查询逻辑更直白,适合小数据量或对窗口函数不熟悉的场景。

内容的提问来源于stack exchange,提问作者Olivia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 07:47:10