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

基于billback_id值选择列的SQL JOIN查询报错求助

问题分析与解决方案

首先看你遇到的语法错误,核心问题有两个:

  • 你给CASE表达式起的别名bsih.total不合法,SQL里列别名不能直接用.,要么改成普通名称(比如selected_total),要么用方括号括起来(比如[bsih.total],但不推荐这么做,容易混淆)。
  • 你的SELECT里写了bsih.invoice_amount,但子查询bsih里根本没选这个字段,执行时会提示找不到该列,得要么在子查询里加上invoice_amount,要么删掉这个字段。

修正后的查询语句如下:

select
    -- 如果需要invoice_amount,先在子查询里添加该字段,否则删掉这一行
    bsih.invoice_amount, 
    case when bhh.billback_id = 3 then bhh.ctv else bsih.total end as selected_total
from [movement].[dbo].[billback_header_history] as bhh
left join
(
    select 
        invoice_number, 
        invoice_extension,
        store_number, 
        sum(ctv) as total,
        invoice_amount -- 这里加上你需要的字段
    from [movement].[dbo].[bsih]
    where ctv <> 0
    group by invoice_number, invoice_extension, store_number, invoice_amount -- GROUP BY里也要加上
) as bsih
on bhh.invoice_number = bsih.invoice_number
where last_movement_update between '2022/01/08' and '2022/01/14'

关于你问的「能不能在JOIN语句中实现该逻辑」:
其实可以,但完全没必要这么做——因为你的需求是根据条件选择不同列的值,不是根据条件决定是否关联表,在SELECT里用CASE表达式是最直接高效的写法。如果硬要在JOIN里处理,反而会让逻辑变复杂,比如需要拆分关联逻辑或者用子查询嵌套,反而增加维护成本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:45:45