【问题标题】:Group by select case or subselects按选择案例或子选择分组
【发布时间】:2021-03-27 22:06:37
【问题描述】:

我有一个产品列表,我想按组件对它们进行分组。 我所说的 SIAC 是每个最终产品的主要组件,有时客户会购买此组件而不是产品,因此我需要将最终组件(产品的 SIAC)和 SIAC 作为产品本身来计算。该选择会返回我为挂单提供服务所需的所有 SIAC。

select      isnull((select case when l.codart like 'SIAC%' 
                then l.codart
                else (select e.codartc from escandallo e where e.codartp = l.codart and e.codartc like 'SIAC%') 
                end as SIAC), 'NO SIAC') as 'REF',
            sum(l.unidades - l.unianulada - l.uniservida) AS PENDING_UNITS
from        LINEPEDI l 
where       ((l.unidades - l.unianulada - l.uniservida) * l.precio) > 0
            and isnull((select case when l.codart like 'SIAC%' 
                then l.codart 
                else (select e.codartc from escandallo e where e.codartp = l.codart and e.codartc like 'SIAC%') 
                end as SIAC), 'NO SIAC') like 'SIAC%'
group by    l.codart
order by    l.codart asc

但我不知道如何按“REF”分组

按最终产品 (l.codart) 分组返回此

REF         PENDING_UNITS
SIACZM016   300
SIACZM017   1200
SIACZM017   500
SIACZM017   900
SIACZM018   400

因此有 3 个最终产品具有相同的主要成分 (SIACZM017)。

如何按此语句分组?

isnull((select case when l.codart like 'SIAC%' 
                    then l.codart
                    else (select e.codartc from escandallo e where e.codartp = l.codart and e.codartc like 'SIAC%') 
                    end as SIAC), 'NO SIAC')

非常感谢

【问题讨论】:

    标签: sql sql-server tsql group-by


    【解决方案1】:

    只需使用横向连接,不仅可以按它进行分组,而且可以避免重复。

    select R.Ref
        , sum(l.unidades - l.unianulada - l.uniservida) AS PENDING_UNITS
    from LINEPEDI l 
    cross apply (
        select isnull((
            select case when l.codart like 'SIAC%' 
                then l.codart 
                else (select e.codartc from escandallo e where e.codartp = l.codart and e.codartc like 'SIAC%') 
                end as SIAC), 'NO SIAC') Ref
    ) R
    where ((l.unidades - l.unianulada - l.uniservida) * l.precio) > 0
    and R.Ref like 'SIAC%'
    group by R.Ref
    order by R.Ref asc;
    

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 2010-12-22
      • 2020-04-04
      相关资源
      最近更新 更多