Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按选择案例或子选择分组_Sql_Sql Server_Tsql_Group By - Fatal编程技术网

Sql 按选择案例或子选择分组

Sql 按选择案例或子选择分组,sql,sql-server,tsql,group-by,Sql,Sql Server,Tsql,Group By,我有一个产品列表,我想根据它们的组件对它们进行分组。 我所命名的SIAC是每个最终产品的主要组件,有时客户购买此组件而不是产品,因此我需要将最终组件(产品的SIAC)和SIAC作为产品本身计算在内。该select返回为待定订单提供服务所需的所有SIAC select isnull((select case when l.codart like 'SIAC%' then l.codart else (select e.co

我有一个产品列表,我想根据它们的组件对它们进行分组。 我所命名的SIAC是每个最终产品的主要组件,有时客户购买此组件而不是产品,因此我需要将最终组件(产品的SIAC)和SIAC作为产品本身计算在内。该select返回为待定订单提供服务所需的所有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')

非常感谢

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

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;

非常感谢。它起作用了