sql >> Base de Datos >  >> RDS >> Sqlserver

filtrado de resultados sabios de trimestre en sql

Para concatenar los valores de varias filas, deberá implementar FOR XML PATH, similar a esto:

;with cte as
(
  select t.cust_id,
    sum(target) target,
    d.qtr,
    t.year,
    t.fiscal_id
  from yourtable t
  inner join
  (
    select 4 mth, 'Q1' qtr union all
    select 5 mth, 'Q1' qtr union all
    select 6 mth, 'Q1' qtr union all
    select 7 mth, 'Q2' qtr union all
    select 8 mth, 'Q2' qtr union all
    select 9 mth, 'Q2' 
  ) d
    on t.month = d.mth
  group by t.cust_id, d.qtr, t.year, t.fiscal_id
) 
select distinct cust_id,
  STUFF(
         (SELECT ' / ' + cast(c2.target as varchar(10))
          FROM cte c2
          where c1.cust_id = c1.cust_id
            and c1.year = c2.year
            and c1.fiscal_id = c2.fiscal_id
          FOR XML PATH (''))
          , 1, 2, '')  AS target,
  STUFF(
         (SELECT ' / ' + c2.qtr
          FROM cte c2
          where c1.cust_id = c1.cust_id
            and c1.year = c2.year
            and c1.fiscal_id = c2.fiscal_id
          FOR XML PATH (''))
          , 1, 2, '')  AS qtr,
  year,
  fiscal_id
from cte c1;

Consulte SQL Fiddle con demostración