0

次のような Microsoft SQL Server 2008 R2 テーブルがあります。

CREATE TABLE [dbo].[CRSpendByPeriod](
[crmcref] [char](6) NOT NULL,
[year] [numeric](5, 0) NOT NULL,
[mtdvalue_1] [numeric](10, 2) NULL,
[mtdvalue_2] [numeric](10, 2) NULL,
[mtdvalue_3] [numeric](10, 2) NULL,
[mtdvalue_4] [numeric](10, 2) NULL,
[mtdvalue_5] [numeric](10, 2) NULL,
[mtdvalue_6] [numeric](10, 2) NULL,
[mtdvalue_7] [numeric](10, 2) NULL,
[mtdvalue_8] [numeric](10, 2) NULL,
[mtdvalue_9] [numeric](10, 2) NULL,
[mtdvalue_10] [numeric](10, 2) NULL,
[mtdvalue_11] [numeric](10, 2) NULL,
[mtdvalue_12] [numeric](10, 2) NULL,
[ytdvalue] [numeric](10, 2) NULL,) 
ON [PRIMARY]
GO

year = 2013 and 2014返品先を選択した場合2 rows per crmcref(口座番号)

私は2014sum mtdvalue_5, mtdvalue_6, mtdvalue_7, mtdvalue_8, mtdvalue_9, mtdvalue_10, mtdvalue_11, mtdvalue_12 where year is 2013 and then add mtdvalue_1, mtdvalue_2, mtdvalue_3, mtdvalue_4年がどこにある必要があります

基本的に、データは暦年に分割されており、会計年度に基づいて計算する必要があります。

事前にどんな助けにも乾杯。

ミム

4

2 に答える 2

2

あなたの問題は sql 構文ではなく、正規化にあります。第 1 正規形では、クエリはより簡単になります。最初の CTE ステートメントは、正規化されたスキーマをシミュレートすることを目的としています。

;with 

-- here normalized table
norm as (
  select [crmcref] ,[year] ,[mtdvalue_1] as value, 1 as my_month
  from [dbo].[CRSpendByPeriod] union all
  select [crmcref] ,[year] ,[mtdvalue_2] as value, 2 as my_month
  from [dbo].[CRSpendByPeriod] union all
  ...
  select [crmcref] ,[year] ,[mtdvalue_12] as value, 12 as my_month
  from [dbo].[CRSpendByPeriod]
),

-- here fiscal year
fiscal_year as (
   select 0 as deltaYear, 1 as fiscal_month union all
   select 0 as deltaYear, 2 as fiscal_month union all
   select 0 as deltaYear, 3 as fiscal_month union all
   select 0 as deltaYear, 4 as fiscal_month union all
   select 1 as deltaYear, 5 as fiscal_month union all
   select 1 as deltaYear, 6 as fiscal_month union all
   select 1 as deltaYear, 7 as fiscal_month union all
   select 1 as deltaYear, 8 as fiscal_month union all
   ...
   select 1 as deltaYear, 12 as fiscal_month
),

-- finaly the join
select crmcref, sum( value ), [year] + deltaYear
from norm 
inner join fiscal_year on norm.my_month = fisca_year.fiscal_month
group by crmcref, [year] + deltaYear
于 2013-09-05T08:28:19.203 に答える
0

does this help you?

select  [crmcref],
sum(isnull(mtdvalue_1,0)) as M1,sum(isnull(mtdvalue_2,0)) as M2,sum(isnull(mtdvalue_3,0)) as M3,
sum(isnull(mtdvalue_4,0)) as M4,sum(isnull(mtdvalue_5,0)) as M5,sum(isnull(mtdvalue_6,0)) as M6,
sum(isnull(mtdvalue_7,0)) as M7,sum(isnull(mtdvalue_8,0)) as M8,sum(isnull(mtdvalue_9,0)) as M9,
sum(isnull(mtdvalue_10,0)) as M10,sum(isnull(mtdvalue_11,0)) as M11,sum(isnull(mtdvalue_12,0)) as M12 
from [CRSpendByPeriod] where year in (2013,2014) group by [crmcref]
于 2013-09-05T08:42:05.917 に答える