在SQL Query中计算(除)两个求和字段

时间:2015-04-28 22:29:09

标签: sql

我有这个问题:

Select FMUM.DimSubscriptionKey, sum(FMUM.TotalUnits) as TotalUnits, sum(FMUM.AI_NormalizedUsage) as AI_NormalizedUsage 
 from [AI_DataMart].[AzureViews].[v_FactMeteredUsageMonthly] as FMUM
join [AI_DataMart].[AzureViews].[v_DimServiceExtended] as SE on(FMUM.DimServiceKey = SE.DimServiceKey)
join [AI_DataMart].[AzureViews].[v_DimAccount] as A on(FMUM.DimAccountKey = A.DimAccountKey)
Join [AI_DataMart].[AzureViews].[v_DimSubscription] as SU on(FMUM.DimSubscriptionKey = SU.DimSubscriptionKey)
where 
 FMUM.DimDateKey >= '20150201'And FMUM.DimDateKey <= '20150331'
And SE.Workload = 'SQLDB'
And SE.ResourceName != 'SQL Reporting Hours'
And (SU.AI_BillingType = 'EA' or SU.AI_BillingType = 'Direct') 
 AND SU.IsFraudIdentified = 0
AND SU.AI_IsTest = 0
AND SU.DimBillingSystemKey = 1
AND FMUM.DimSubscriptionKey = '4707785'
group by FMUM.DimSubscriptionKey

返回此结果:

DimSubscriptionKey TotalUnits AI_NormalizedUsage 4707785 24.77043700 21.08775630

我需要得到的并且无法上班的是第4列(AI_NormaliedUsage / TotalUnits)

但是当我将它添加到查询中时:

Select FMUM.DimSubscriptionKey, sum(FMUM.TotalUnits) as TotalUnits, sum(FMUM.AI_NormalizedUsage) as AI_NormalizedUsage, (AI_NormalizedUsage / TotalUnits) 
 from [AI_DataMart].[AzureViews].[v_FactMeteredUsageMonthly] as FMUM
join [AI_DataMart].[AzureViews].[v_DimServiceExtended] as SE on(FMUM.DimServiceKey = SE.DimServiceKey)
join [AI_DataMart].[AzureViews].[v_DimAccount] as A on(FMUM.DimAccountKey = A.DimAccountKey)
Join [AI_DataMart].[AzureViews].[v_DimSubscription] as SU on(FMUM.DimSubscriptionKey = SU.DimSubscriptionKey)
where 
 FMUM.DimDateKey >= '20150201'And FMUM.DimDateKey <= '20150331'
And SE.Workload = 'SQLDB'
And SE.ResourceName != 'SQL Reporting Hours'
And (SU.AI_BillingType = 'EA' or SU.AI_BillingType = 'Direct') 
 AND SU.IsFraudIdentified = 0
AND SU.AI_IsTest = 0
AND SU.DimBillingSystemKey = 1
AND FMUM.DimSubscriptionKey = '4707785'
group by FMUM.DimSubscriptionKey, (AI_NormalizedUsage / TotalUnits) 

我没有得到预期的结果:

DimSubscriptionKey  TotalUnits  AI_NormalizedUsage  (No column name)
4707785 1.45831000  0.70567620  0.48389999382847268413
4707785 3.39577900  3.28609533  0.96769999755578911348
4707785 9.49984800  9.19300290  0.96769999898945751553
4707785 3.41661200  3.30625543  0.96769999929754973640
4707785 4.49992800  2.17751515  0.48389999795552284392
4707785 2.49996000  2.41921129  0.96769999919998719979

我想要的是

DimSubscriptionKey TotalUnits AI_NormalizedUsge NewCalculatedField<br>
4707785 24.770437   21.0877563  0.851327585

我错过了什么?架起我的大脑!

2 个答案:

答案 0 :(得分:3)

如果您在同一个select语句中引用派生列,则无法通过别名引用它们,则需要复制计算,或将其包装在另一个select语句中。

在不知道基础表的任何内容的情况下,此修复程序应该有效:

GetType

答案 1 :(得分:1)

抱歉,我无法发表评论,但你试过这个:

Ringtone.isPlaying

任何一方都不需要小组。