这是我正在阅读的表格:
sk_calendar_week | ClientId | Amount
------------------+-----------+-------
2014001 | 1 | 550
2014002 | 2 | 900
2014003 | 3 | 389
2014004 | 4 | 300
以下是我使用的查询:
declare @IniDate as int = 20140610, @EndDate as int = 20150425
select
COUNT(distinct sk_calendar_week) WeekQ,
COUNT(distinct sk_calendar_Month) MonthQ
from
(select
sk_date, sk_calendar_week, sk_calendar_Month,
ClientId, Amount
from
TableA
where
Sk_Date between @IniDate and @EndDate) q1
此查询返回:
WeekQ | MonthQ
------+-------
4 | 1
如何将WeekQ
中的4除以金额(550/4; 900/4; 389/4 ...),以获得这样的结果?
sk_calendar_week | ClientId | Amount | Division
-------------------+----------+--------+---------
2014001 | 1 | 550 | 137.5
2014002 | 2 | 900 | 225
2014003 | 3 | 389 | 97.25
2014004 | 4 | 300 | 75
答案 0 :(得分:2)
您可以使用第一个查询来填充局部变量,并在第二个查询中使用它,如下所示:
declare @IniDate as int = 20140610,
@EndDate as int = 20150425,
@Week int
select @Week = COUNT(distinct sk_calendar_week)
from TableA where Sk_Date between @IniDate and @EndDate )
Select sk_calendar_week,
ClientId,
Amount,
cast(Amount as decimal(8,2)) / @Week as Divsion
子查询版本会受到性能影响,但这是一个例子:
Select sk_calendar_week,
ClientId,
Amount,
cast(Amount as decimal(8,2)) /
(select COUNT(distinct sk_calendar_week)
from TableA where Sk_Date between @IniDate and @EndDate ) as Divsion
答案 1 :(得分:1)
尝试使用窗口功能:
declare @IniDate as int = 20140610, @EndDate as int = 20150425
select *, amount*1.0/count(*) over() as division
from(
select sk_date
,sk_calendar_week
,sk_calendar_Month
,ClientId
,Amount
from TableA
where Sk_Date between @IniDate and @EndDate
)q1