0

次のような構造のテーブルがあります

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    Q1      2013 1
234     450    Q2      2013 1

第 1 四半期に 4、5、6 か月、第 2 四半期に 7、8、9 か月など

4

1 に答える 1

2

monthとを別の列に格納しているyearため、結果を取得する 1 つの方法は、月と四半期を参照する派生テーブルを使用し、そのデータに結合することです。

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;

SQL Fiddle with Demoを参照してください。

于 2013-06-24T13:42:19.797 に答える