【问题标题】:Subquery from another table in Case when conditionCase when 条件下来自另一个表的子查询
【发布时间】:2020-08-08 04:39:13
【问题描述】:

我正在尝试编写一个查询,我想根据作为子查询的条件对价格列求和。

我的查询:

select
  fund.FundName, 
  SUM(Case when (
        Select Top 1 bitValue 
        from table 1 
        where table1.id = Company.id and table1.field = 25
        ) = 1 then price else 0 end) as 'TotalPrice'
from
Fund left outer join Company on Company.fundId=fund.id 
group by
fund.fundName

它引发错误:无法对包含聚合或子查询的表达式执行聚合函数。

实现这一目标的最佳替代方法是什么。

【问题讨论】:

  • Top 1 是否存在于 MySQL 中?我认为您的数据库标签错误。这可能是 Sybase 或 SQL Server。
  • 我的错,这是一个 sql server 查询
  • 不,这是另一个问题。我在这个子查询之外使用了 join 并且没有工作。此外,我使用的是 Top 1,但我在任何地方都找不到答案。我知道 case 不允许多个返回值。所以我想知道实现这种情况的替代方法是什么。
  • 存在时可以试试??

标签: sql-server subquery case aggregate-functions


【解决方案1】:

希望这适用于您的案例:

选择 基金.基金名称, S.总价格 来自基金 LEFT OUTER JOIN COMPANY ON COMPANY.FUNDID=FUND.ID LEFT JOIN (SELECT CASE WHEN BITVALUE=1 THEN SUM(PRICE) ELSE 0 END as 'TotalPrice',table1.ID 从表 1 其中 table1.id = Company.id 和 table1.field = 25 GROUP BY table1.ID ) S ON S.ID=Company.id 通过...分组 基金.基金名称

【讨论】:

    【解决方案2】:

    未经测试显然没有提供样本数据。

    select fund.FundName
      ,SUM(Case when table1.id is not null then price else 0 end) as 'TotalPrice'
    from Fund
    left outer join Company on Company.fundId = fund.id
    left outer join (
        select distinct id
        from table1
        where field = 25
            and bitvalue = 1
    ) table1 on table1.id = Company.id
    group by fund.fundName
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-04
      • 2023-04-01
      • 2021-10-03
      • 1970-01-01
      • 2022-12-15
      • 2021-05-08
      • 2019-02-01
      • 1970-01-01
      相关资源
      最近更新 更多