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(帐号)

我需要知道2014 年sum 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 语法,而在于规范化。在第一范式中,您的查询会更容易。第一个 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

这对你有帮助吗?

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 回答