四分之一年明智的结果过滤sql

时间:2013-06-24 16:04:09

标签: sql-server-2008

我的表格结构如下

id cust_id target month year fiscal_ID
1  234     50     4     2013 1 
2  234     50     5     2013 1
3  234     50     6     2013 1
4  234     150    7     2013 1
5  234     150    8     2013 1
6  234     150    9     2013 1

我需要得到如下结果

cust_id target  quarter year fiscal_ID
234     150/450 Q1/Q2   2013 1
第一季度为4,5,6个月,第二季度为7,8,9等

1 个答案:

答案 0 :(得分:1)

为了将多行中的值连接在一起,您需要实现FOR XML PATH,类似于:

;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;

请参阅SQL Fiddle with Demo